Version: 2020.3
Language : English
Writing UXML Templates
UXML elements reference

Loading UXML from C

To build user interface from a UXML template, you must first load the template into a VisualTreeAsset:

var template = EditorGUIUtility.Load("path/to/file.uxml") as VisualTreeAsset;

or more directly :

var template = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("path/to/file.uxml");

You can then build the visual tree that this represents and attach it to a parent element:

template.CloneTree(parentElement, slots);

In the statement above, the <UXML> element in the template isn’t translated to aVisualElement. Instead, all of its children are attached to the element specified by parentElement.

Once the template is instantiated, you can retrieve specific elements from the visual element tree with UQuery: Unity’s implementation of JQuery/Linq.

For example, the following code demonstrates how to create a new EditorWindow and load a UXML file as its content:


public class MyWindow : EditorWindow  {
    [MenuItem ("Window/My Window")]
    public static void  ShowWindow () {
        EditorWindow w = EditorWindow.GetWindow(typeof(MyWindow));

        VisualTreeAsset uiAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/MyWindow.uxml");
        VisualElement ui = uiAsset.CloneTree(null);

        w.rootVisualElement.Add(ui);
    }

    void OnGUI () {
        // Nothing to do here, unless you need to also handle IMGUI stuff.
    }
}

  • 2018–11–02 Page amended
Writing UXML Templates
UXML elements reference