Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Basics on referencing cloned trees?

Discussion in 'UI Toolkit' started by Stardog, Aug 3, 2019.

  1. Stardog

    Stardog

    Joined:
    Jun 28, 2010
    Posts:
    1,910
    I need some help on what the convention is to reference things that I've loaded from XML, then added as a VisualElement. I'm trying to add some items to a node.

    CloneTree returns a VE, but CloneTree(parent) doesn't, so I can't access the thing I added without a query? Also, visualElement.Add doesn't return the VE you're adding, either.

    To me it should be as easy as this:
    Code (csharp):
    1. VisualElement node = nodeContainerXML.CloneTree(mainVE); // Can't because it returns void
    2.  
    3. VisualElement item = nodeItemXML.CloneTree(node);
    4. VisualElement item2 = nodeItemXML.CloneTree(node);
    5. VisualElement item3 = nodeItemXML.CloneTree(node);
    6.  
    7. item.style.backgroundColor....red
    8. item2.style.backgroundColor....green
    9. item3.style.backgroundColor....blue
    I don't see how I reliably find anything with a query unless it has a unique class added to it.

    Also, how do I format a query for an element with multiple classes:
    Code (csharp):
    1. class="class1 class2 class3"
    We really need a CloneTree() that returns a VisualElement that doesn't parent it to a TemplateContainer...And CloneTree(VisualElement ve) that returns the VE.
     
    Last edited: Aug 3, 2019
  2. uMathieu

    uMathieu

    Unity Technologies

    Joined:
    Jun 6, 2017
    Posts:
    396
    The UXML file format allows you to have more that one root element. That's why the CloneTree either create a root element for you, fill it and return it or can its content to the element you pass directly.

    If you don't want to use UQuery, and you are sure that you have only 1 element in your UXML, you can try this instead:

    Code (CSharp):
    1. int lastIndex = mainVE.childCount;
    2. nodeContainerXML.CloneTree(mainVE);
    3. var node = mainVE[lastIndex];
    4.  
    To Query an element that has multiple classes you do:
    Code (CSharp):
    1.  root.Q<VisualElement>(null, "class1", "class2", "class3");
    The first argument is for the name property so we pass null. Then all the others are for classes