包含此页的版本:
不含此页的版本:
版本: 2023.2+
此示例演示如何在自定义编辑器窗口中创建可绑定的自定义控件。
此示例创建绑定到具有 double 数据类型的属性的自定义控件。您可以调整此示例以绑定到具有其他数据类型(如字符串或整数)的属性。
您可以在此 GitHub 存储库中找到此示例创建的已完成文件。
本指南适用于熟悉 Unity 编辑器、UI 工具包和 C# 脚本的开发人员。在开始之前,请熟悉以下内容:
创建一个 C# 类来定义自定义控件。
ExampleField以存储您的文件。ExampleField文件夹中,创建一个名为ExampleField.cs并将其内容替换为以下内容: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.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 显示在“层次结构”窗口中,并在视口用户在屏幕上应用的可见区域。ExampleField文件夹中,创建一个名为ExampleFieldComponent.cs并将其内容替换为以下内容:using UnityEngine;
namespace UIToolkitExamples
{
public class ExampleFieldComponent : MonoBehaviour
{
[SerializeField]
double m_Value;
}
}
ExampleField文件夹中,创建一个名为Editor.Editor文件夹中,创建一个名为ExampleFieldCustomEditor.cs并将其内容替换为以下内容: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在项目窗口一个窗口,显示您的内容Assets文件夹(项目选项卡)更多信息ExampleField.uxml进入 Inspector 窗口中的 Uxml 框。ExampleFieldComponent组件添加到游戏对象。自定义控件显示在检查器中,默认值为0用于绑定目标。如果更改基础 double 属性的值,UI 会反映该更改。