How to access an instance of VisualElement that is created by VisualTreeAsset.CloneTree?

I’m trying to create more than one instances using CloneTree in script. I want to make the new instance be a child of another VisualElement, so I’m using CloneTree instead of Instantiate. However, CloneTree doesn’t return anything different to Instantiate, so I don’t know how to access the instance because there are more than one instances of the same VisualTreeAsset, so their names are identical. How can I access the VisualElement that is created by CloneTree?

If you’re using the CloneTree overload that just takes a VisualElement, the root is the VisualElement you passed. There is also an overload with the signature CloneTree(VisualElement target, out int firstElementIndex, out int elementAddedCount) which gives you the range of children of target that were added from the VisualTreeAsset. For both the overloads that take a VisualElement parameter, you are adding to an existing element, so you don’t have a unique root. For the other overloads, you get back a TemplateContainer which is the root of the cloned tree. If you want access to a unique root per tree, then just use Instantiate and add the returned TemplateContainer to the VisualElement you want to add them to.

2 Likes

Thank you! It works very well. I didn’t know that there was such an overload. I tried to search CloneTree at Unity manual but I couldn’t see that :frowning: