版本:2021.3+
此示例演示了如何使用 UXML 模板设置绑定路径。
此示例创建了一个资源菜单项。该菜单创建一个 GameSwitch 资源,其中包含三个绑定到 GameSwitch 对象属性的模板实例。
您可以在此 GitHub 代码仓库中找到此示例创建的完整文件。
本指南适用于熟悉 Unity 编辑器、UI 工具包和 C# 脚本的开发者。在开始之前,请熟悉以下内容:
创建脚本以定义 GameSwitch 结构,并创建一个自定义资源来保存 GameSwitch 结构的属性。
使用任何模板在 Unity 中创建项目。
在项目 (Project) 窗口中,创建一个名为 bind-uxml-template 的文件夹来存储所有文件。
创建一个名为 GameSwitch.cs 的 C# 脚本,并将其内容替换为以下内容:
using System;
[Serializable]
public struct GameSwitch
{
public string name;
public bool enabled;
}
创建一个名为 GameSwitchesAsset.cs 的 C# 脚本,并将其内容替换为以下代码:
using UnityEngine;
[CreateAssetMenu(menuName = "UIToolkitExamples/GameSwitches")]
public class GameSwitchesAsset : ScriptableObject
{
public GameSwitch useLocalServer;
public GameSwitch showDebugMenu;
public GameSwitch showFPSCounter;
// Use the Reset function to provide default values
public void Reset()
{
useLocalServer = new GameSwitch() { name = "Use Local Server", enabled = false };
showDebugMenu = new GameSwitch() { name = "Show Debug Menu", enabled = false };
showFPSCounter = new GameSwitch() { name = "Show FPS Counter", enabled = true };
}
}
创建一个可用于每个 GameSwitch 结构实例的 UXML 模板以及使用该模板的 UXML 文件。
创建一个名为 game_switch.uxml 的__ UI__(即用户界面,User Interface)让用户能够与您的应用程序进行交互。Unity 目前支持三种 UI 系统。更多信息
See in Glossary 文档,并将其内容替换为以下内容:
<UXML xmlns="UnityEngine.UIElements" xmlns:ue="UnityEditor.UIElements">
<Box style="flex-direction: row;">
<Toggle binding-path="enabled" />
<TextField binding-path="name" readonly="true" style="flex-grow: 1;"/>
</Box>
</UXML>
在 bind-uxml-template 文件夹中,创建一个名为 Editor 的文件夹。
在 Editor 文件夹中,创建一个名为 game_switches_editor.uxml 的 UI 文档,并将其内容替换为以下内容:
<UXML xmlns="UnityEngine.UIElements" xmlns:ue="UnityEditor.UIElements">
<Template name="switch" src="../game_switch.uxml"/>
<Instance template="switch" binding-path="useLocalServer" />
<Instance template="switch" binding-path="showDebugMenu" />
<Instance template="switch" binding-path="showFPSCounter" />
</UXML>
注意:这是自定义编辑器的主 UXML 文件。每个属性都通过 Instance 的 binding-path 属性绑定到 game_switch.uxml 实例。
创建一个脚本来为 GameSwitchesAsset 注册自定义编辑器。
创建一个名为 GameSwitchesEditor.cs 的 C# 脚本,并将其内容替换为以下内容:
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace UIToolkitExamples
{
[CustomEditor(typeof(GameSwitchesAsset))]
public class GameSwitchesEditor : Editor
{
[SerializeField]
VisualTreeAsset visualTreeAsset;
public override VisualElement CreateInspectorGUI()
{
return visualTreeAsset.CloneTree();
}
}
}
在 GameSwitchesEditor.cs 的检视 (Inspector) 窗口中,将 game_switches_editor.uxml 文件分配给 Visual Tree Asset 字段。
Assets 文件夹中创建新资源。GameSwitchesAsset.useLocalServer、GameSwitchesAsset.showDebugMenu 和 GameSwitchesAsset.showFPSCounter 属性的开关和文本字段。