Created
May 31, 2024 13:54
-
-
Save SolarianZ/65735353bb510e1e0c55b638ee1a3c99 to your computer and use it in GitHub Desktop.
{"category": "Unity Engine/Editor/Extensions", "keywords": "Unity, Editor, Find, Panel, rootVisualElement, Name"} Find panel's rootVisualElement by panel name.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Reflection; | |
using UnityEngine.UIElements; | |
public static VisualElement FindPanelRootVisualElementByPanelName(string panelName) | |
{ | |
// UnityEngine.UIElements.UIElementsUtility.GetAllPanels | |
// UnityEngine.UIElements.UIElementsUtility.GetPanelsIterator | |
// UnityEngine.UIElements.Panel.name | |
// UnityEngine.UIElements.Panel.visualTree.name | |
BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; | |
Assembly assembly = typeof(VisualElement).Assembly; | |
Type typeUieUtil = assembly.GetType("UnityEngine.UIElements.UIElementsUtility"); | |
MethodInfo miGetPanelsIter = typeUieUtil.GetMethod("GetPanelsIterator", bindingFlags); | |
IEnumerator panelsIter = (IEnumerator)miGetPanelsIter.Invoke(null, null); | |
Type typePanel = assembly.GetType("UnityEngine.UIElements.Panel"); | |
Type typeKvIntPanel = typeof(KeyValuePair<,>).MakeGenericType(typeof(int), typePanel); | |
PropertyInfo piValue = typeKvIntPanel.GetProperty("Value"); | |
PropertyInfo piName = typePanel.GetProperty("name", bindingFlags); | |
PropertyInfo piVisualTree = typePanel.GetProperty("visualTree", bindingFlags); | |
while (panelsIter.MoveNext()) | |
{ | |
object kvIntPanel = panelsIter.Current; | |
object currPanelObj = piValue.GetValue(kvIntPanel, null); | |
string currPanelName = (string)piName.GetValue(currPanelObj, null); | |
VisualElement visualTree = null; | |
if (string.IsNullOrEmpty(currPanelName)) | |
{ | |
visualTree = (VisualElement)piVisualTree.GetValue(currPanelObj, null); | |
currPanelName = visualTree.name; | |
} | |
if (currPanelName == panelName) | |
{ | |
visualTree ??= (VisualElement)piVisualTree.GetValue(currPanelObj, null); | |
return visualTree; | |
} | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment