Version: 2020.1
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 is not 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
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961