版本: 2021.3+
此示例演示了如何在绑定序列化属性更改时接收回调。
此示例创建一个自定义编辑器窗口,其中包含一个文本字段,该文本字段绑定到场景中游戏对象Unity 场景中的基本对象,可以表示角色、道具、场景、摄像机、航路点等。游戏对象的功能由附加到它的组件定义。 更多信息
在 词汇表 中查看的名称。
 
您可以在此GitHub 存储库中找到示例的完整文件。
本指南适用于熟悉 Unity 编辑器、UI(用户界面) 允许用户与您的应用程序交互。Unity 目前支持三种 UI 系统。 更多信息
在 词汇表 中查看 工具包和 C# 脚本的开发人员。在开始之前,请熟悉以下内容
创建一个 C# 脚本,该脚本
CheckName() 方法TrackPropertyValue() 扩展方法注册该方法TrackPropertyValue() 之前调用 Unbind()。VisualElement 只能在任何给定时间跟踪一个属性。
在 Unity 中创建一个使用任何模板的项目。
在项目窗口显示您的 Assets 文件夹内容的窗口(项目选项卡) 更多信息
在 词汇表 中查看中,创建一个名为 callback-SerializedProperty-changes 的文件夹来存储您的文件。
在 callback-SerializedProperty-change 文件夹中,创建一个名为 Editor 的文件夹。
在 Editor 文件夹中,创建一个名为 SimpleBindingPropertyTrackingExample.cs 的 C# 脚本,并将它的内容替换为以下内容
using UnityEditor;
using UnityEngine;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace UIToolkitExamples
{
    public class SimpleBindingPropertyTrackingExample : EditorWindow
    {
        TextField m_ObjectNameBinding;
        [MenuItem("Window/UIToolkitExamples/Simple Binding Property Tracking Example")]
        public static void ShowDefaultWindow()
        {
            var wnd = GetWindow<SimpleBindingPropertyTrackingExample>();
            wnd.titleContent = new GUIContent("Simple Binding Property Tracking");
        }
            
        public void CreateGUI()
        {
            m_ObjectNameBinding = new TextField("Object Name Binding");
            rootVisualElement.Add(m_ObjectNameBinding);
            OnSelectionChange();
        }
        public void OnSelectionChange()
        {
            GameObject selectedObject = Selection.activeObject as GameObject;
            if (selectedObject != null)
            {
                // Create the SerializedObject from the current selection
                SerializedObject so = new SerializedObject(selectedObject);
                // Note: the "name" property of a GameObject is actually named "m_Name" in serialization.
                SerializedProperty property = so.FindProperty("m_Name");
                    
                // Ensure to use Unbind() before tracking a new property
                m_ObjectNameBinding.Unbind();
                m_ObjectNameBinding.TrackPropertyValue(property, CheckName);
                // Bind the property to the field directly
                m_ObjectNameBinding.BindProperty(property);
                CheckName(property);
            }
            else
            {
                // Unbind any binding from the field
                m_ObjectNameBinding.Unbind();
            }
        }
        void CheckName(SerializedProperty property)
        {
            if (property.stringValue == "GameObject")
            {
                m_ObjectNameBinding.style.backgroundColor = Color.red * 0.5f;
            }
            else
            {
                m_ObjectNameBinding.style.backgroundColor = StyleKeyword.Null;
            }
        }
    }
}
GameObject,则标签的背景颜色将变为深红色。