Search Unity

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

Discussion in 'UI Toolkit' started by Nothke, Jan 26, 2020.

  1. Nothke

    Nothke

    Joined:
    Dec 2, 2012
    Posts:
    112
    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.
     
  2. uDamian

    uDamian

    Unity Technologies

    Joined:
    Dec 11, 2017
    Posts:
    1,231
    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:
    https://github.com/Unity-Technologi.../Assets/Tanks/Scripts/Managers/GameManager.cs
     
    Nothke likes this.
  3. Nothke

    Nothke

    Joined:
    Dec 2, 2012
    Posts:
    112
    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.

    Code (CSharp):
    1.     IEnumerator Start()
    2.     {
    3.         // Won't work without skipping a frame:
    4.         yield return null;
    5.  
    6.         PanelRenderer panel = GetComponent<PanelRenderer>();
    7.         var root = panel.visualTree;
    8.  
    9.         root.Add(new Label("Something!"));
    10.     }
     
    Deksover likes this.