Reputation: 326
I want to create a few Character Panels dynamically in runtime. I've created SingleCharacter.uxml and I can set a few copies of that by dragging it handly to hierarchy, but I need to do it through c# script because the player can have 1 character, 3 characters, etc.
In old UI system I would just instantiate CharacterPanel prefab and set proper parent.
How can I do this? I can't find any information in the documentation.
Upvotes: 1
Views: 1959
Reputation: 326
So, here is an answer. We have to just add serialized field with type VisualTreeAsset where we can attack reference to uxml template. Then using CloneTree() method we can add how many elements we want.
public class CharacterPanelController: MonoBehaviour
{
public VisualTreeAsset singleCharacter;
private void Start() Unity Message | O references
{
var root = GetComponent<UIDocument>().rootVisualElement;
var leftSide = root.Q<VisualElement>(UINames.LeftSide);
for (int i = 0; i < 5; i++)
{
singleCharacter.CloneTree(leftSide);
}
}
}
Upvotes: 1