UIToolkit / UI Builder How do I add elements to a Foldout?

How can I add an element to a foldout via code of UI builder?

The form above I made with the UI Builder window. I can get buttons and toggle elements fine through code.

I’m trying to implement foldout (dd_heading) but cannot for the life of me figure out how to add elements to the foldout. I’ve looked at the documentation but I can’t seem to grasp how I add elements to a foldout.

I can see the child elements in the foldout but don’t know how I can access them.
192402-screenshot-2022-02-09-125637.png

The form is a text editor which can edit Heading text and Body text. User selects the dropdown to switch between Heading & Body.

Hi @oranchad.

I’ve just started working with UI Toolkit and I am trying to do exactly this. By checking out this sample I have managed to achieve what I want.

Basically, what I do to populate a foldout programmatically is serialize a VisualTreeAsset field (an UXML file, basically) where the item I want to populate is designed. Then, all you have to do in your code is clone it and add it to the foldup visual element like this:


[SerializeField] private VisualTreeAsset FoldupItemAsset;

private void Awake()
{
    mainMenuRoot = GetComponent<UIDocument>().rootVisualElement;

    gameModeSelector = mainMenuRoot.Q<Foldout>("GameModeSelector");

    var gameModeButon = FoldupItemAsset.CloneTree();
    //Initialize your item here
    gameModeSelector.Add(gameModeButon);
}

Of course, this is the most basic thing you can do with this. You can implement your own components by extending de VisualElement class and add your own logic there. I am no expert though, so I’m still learnign all this stuff. Hope this helps you out.