Search Unity

  1. All Pro and Enterprise subscribers: find helpful & inspiring creative, tech, and business know-how in the new Unity Success Hub. Sign in to stay up to date.
    Dismiss Notice
  2. Dismiss Notice

Basics on referencing cloned trees?

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

  1. Stardog


    Jun 28, 2010
    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
    3. VisualElement item = nodeItemXML.CloneTree(node);
    4. VisualElement item2 = nodeItemXML.CloneTree(node);
    5. VisualElement item3 = nodeItemXML.CloneTree(node);
    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


    Unity Technologies

    Jun 6, 2017
    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];
    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