Version: 2023.1
Load UXML and USS C# scripts
Find visual elements with UQuery

Instantiate UXML from C# scripts

To build UI from a UXML file, you must first load the file into a VisualTreeAsset, and then use the Instantiate() to instantiate without a parent, which creates a new TemplateContainer, or CloneTree(parent)) to clone inside a parent.

Once the UXML is instantiated, you can retrieve specific elements from the visual tree with UQuery.

The following example creates a custom Editor window and loads a UXML file as its content:

using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor.UIElements;

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.Instantiate();

        w.rootVisualElement.Add(ui);
    }
}

其他资源

Load UXML and USS C# scripts
Find visual elements with UQuery
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961