版本:2023.2+
此示例演示了如何在自定义 Editor 窗口中创建可绑定的自定义控件。
此示例创建了一个绑定到具有双重数据类型的属性的自定义控件。您可以调整此示例以绑定到具有其他数据类型(例如字符串或整数)的属性。
您可以在此 GitHub 代码仓库中找到此示例创建的完整文件。
本指南适用于熟悉 Unity 编辑器、UI 工具包和 C# 脚本的开发者。在开始之前,请熟悉以下内容:
创建一个 C# 类来定义自定义控件。
ExampleField 的文件夹来存储文件。ExampleField 文件夹中创建一个名为 ExampleField.cs 的 C# 脚本,并将其内容替换为以下代码:using UnityEngine.UIElements;
namespace UIToolkitExamples
{
// ExampleField inherits from BaseField with the double type. ExampleField's underlying value, then, is a double.
[UxmlElement]
public partial class ExampleField : BaseField<double>
{
Label m_Input;
// Default constructor is required for compatibility with UXML factory
public ExampleField() : this(null)
{
}
// Main constructor accepts label parameter to mimic BaseField constructor.
// Second argument to base constructor is the input element, the one that displays the value this field is
// bound to.
public ExampleField(string label) : base(label, new Label() { })
{
// This is the input element instantiated for the base constructor.
m_Input = this.Q<Label>(className: inputUssClassName);
}
// SetValueWithoutNotify needs to be overridden by calling the base version and then making a change to the
// underlying value be reflected in the input element.
public override void SetValueWithoutNotify(double newValue)
{
base.SetValueWithoutNotify(newValue);
m_Input.text = value.ToString("N");
}
}
}
ExampleField 文件夹中,创建一个名为 ExampleField.uxml 的__ UI__(即用户界面,User Interface)让用户能够与您的应用程序进行交互。Unity 目前支持三种 UI 系统。更多信息ExampleField.uxml 并将其内容替换为以下内容:<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:example="UIToolkitExamples">
<example:ExampleField label="Binding Target" binding-path="m_Value" />
</ui:UXML>
ExampleField.uxml 可在 UI Builder 中将其打开。ExampleField 在层级视图 (Hierarchy) 窗口中显示,并在 Viewport 中可视化。如果在层级视图 (Hierarchy) 窗口中选择 ExampleField,检视面板 (Inspector) 窗口将显示分配给绑定路径 (Binding Path) 和标签 (Label) 框的值。ExampleField 文件夹中创建一个名为 ExampleFieldComponent.cs 的 C# 脚本,并将其内容替换为以下代码:using UnityEngine;
namespace UIToolkitExamples
{
public class ExampleFieldComponent : MonoBehaviour
{
[SerializeField]
double m_Value;
}
}
ExampleField 文件夹中,创建一个名为 Editor 的文件夹。Editor 文件夹中创建一个名为 ExampleFieldCustomEditor.cs 的 C# 脚本,并将其内容替换为以下代码:using UnityEditor;
using UnityEngine.UIElements;
using UnityEngine;
namespace UIToolkitExamples
{
[CustomEditor(typeof(ExampleFieldComponent))]
public class ExampleFieldCustomEditor : Editor
{
[SerializeField]
VisualTreeAsset m_Uxml;
public override VisualElement CreateInspectorGUI()
{
var parent = new VisualElement();
m_Uxml?.CloneTree(parent);
return parent;
}
}
}
ExampleFieldCustomEditor.cs。ExampleField.uxml 拖入检视面板 (Inspector) 窗口中的 Uxml 框中。ExampleFieldComponent 组件添加到游戏对象。自定义控件在检视面板中显示,绑定目标的默认值为 0。如果更改底层 double 属性的值,UI 会反映该更改。