[Runtime] How to create visual elements from code and render?

Editor UIElements provide a way to build elements from code and render in an editor window by assigning the VisualElement as the root node. But PanelRenderer only seems to use uxml to render UI. How can you pass a visual element tree to a PanelRenderer? Or, altenatively, can you build a uxml at runtime to assign it to the PanelRenderer?

My intention is to use UIElements like IMGUI, as a simple debug window without the runtime cost of IMGUI, but without the need to build uxml elements in the builder.

EditorWindow has its root element called rootVisualElement, while for PanelRenderer it’s called visualTree. Once you have a reference to a PanelRenderer Component panelRenderer, you can access its root element via panelRenderer.visualTree and add/remove/modify any elements you wish in C# without using UXMl, if you wish. It should work the same as with EditorWindows or Inspectors.

See BindMainMenuScreen() function in the demo file for some example usage:

1 Like

I actually tried this, but it didn’t work. It turns out it doesn’t work in Start(), but you have to wait a frame for it to work.

    IEnumerator Start()
    {
        // Won't work without skipping a frame:
        yield return null;

        PanelRenderer panel = GetComponent<PanelRenderer>();
        var root = panel.visualTree;

        root.Add(new Label("Something!"));
    }
1 Like