Search Unity

Question Iterating over all VisualElements in a VisualTreeAsset

Discussion in 'UI Toolkit' started by velosoda0159, Dec 6, 2022.

  1. velosoda0159

    velosoda0159

    Joined:
    Aug 4, 2021
    Posts:
    4
    I am currently working on a tool for my UIToolkit workflow that would generate a script based on all the elements in a given UXML File/VisualTreeAsset. To accomplish this I would like to first iterate over all the visual elements in a VisualTreeAsset. My most progressive attempt looked like this:

    Code (CSharp):
    1. foreach(VisualElement visualElement in m_UIInput.Instantiate().hierarchy.Children())
    2. {
    3.     Debug.Log(visualElement.name);
    4. }
    But this would just give me the first VisualElement in the Tree. Im not too sure what I should use in this case and I couldnt find much about this online so any advice would be awesome!

    The image below is me running the tool on the open uxml file. You can see that theres more visual elements in the market-moreinfo_panel visual element. I would expect to see every elements name appear in the console.

    unity help.PNG
     

    Attached Files:

  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,925
    You're way off the correct subforum, mate: https://forum.unity.com/forums/ui-toolkit.178/

    But you need to do a recursive iteration of all children of the root visual element. It could be as simple as this:
    Code (CSharp):
    1. public static IEnumerable<VisualElement> EnumerateVisualElementHierarchy(this VisualElement element)
    2. {
    3.     yield return element;
    4.  
    5.     foreach (VisualElement childElement in element.Children())
    6.     {
    7.     childElement.EnumerateVisualElementHierarchy();
    8.     }
    9. }
    Which is just an quick and dirty, order-based recursive iterator (a not very performant one, mind you). There are more advanced methods to iterate through a hierarchy of course.
     
    CodeSmile likes this.
  3. velosoda0159

    velosoda0159

    Joined:
    Aug 4, 2021
    Posts:
    4
    Ok let me close and post there my bad first post
     
  4. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,925
    Can't really lock your own threads; I've just reported it so a mod will move it.
     
  5. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    5,964
    If you may need to skip certain elements it would be an alternative to assign a .iterate class to the elements you are interested in and then use query.

    This is how i find all .unity-button elements on my screen in order to generically assign them the onclick event callback. That removes a lot of boilerplate code from the GUI.
     
    spiney199 likes this.