Version: 2022.1
Write UXML Templates
UXML 元素参考

Load UXML from C# scripts

要根据 UXML 模板构建用户界面,必须先将模板加载到 VisualTreeAsset 中:

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

或者采用更直接的方式:

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

然后可以构建表示的视觉树并将其附加到父元素:

template.CloneTree(parentElement, slots);

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

实例化模板后,即可使用 UQuery(Unity 的 JQuery/Linq 实现)从视觉元素树中检索特定元素。

例如,以下代码演示了如何创建新的 EditorWindow 并加载 UXML 文件作为其内容:

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

        w.rootVisualElement.Add(ui);
    }
}
Write UXML Templates
UXML 元素参考