版本:2021.3+
您可以调用 BindProperty() 将元素直接绑定到 SerializedProperty 对象,而不是使用绑定路径。此示例演示了如何通过 BindProperty() 进行绑定。
此示例创建了一个自定义编辑器窗口来更改游戏对象的名称。
您可以在此 GitHub 代码仓库中找到此示例创建的完整文件。
本指南适用于熟悉 Unity 编辑器、UI 工具包和 C# 脚本的开发者。在开始之前,请熟悉以下内容:
BindProperty() 绑定在 C# 中创建一个带有 TextField 的自定义编辑器 Editor 窗口。查找游戏对象的名称属性,然后直接使用 BindProperty() 方法绑定到该属性。
在项目 (Project) 窗口中,创建一个名为 bind-without-binding-path 的文件夹来存储文件。
在 bind-without-binding-path 文件夹中,创建一个名为 Editor 的文件夹。
在 Editor 文件夹中创建一个名为 SimpleBindingPropertyExample.cs 的 C# 脚本,并将其内容替换为以下代码:
using UnityEditor;
using UnityEngine;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace UIToolkitExamples
{
public class SimpleBindingPropertyExample : EditorWindow
{
TextField m_ObjectNameBinding;
[MenuItem("Window/UIToolkitExamples/Simple Binding Property Example")]
public static void ShowDefaultWindow()
{
var wnd = GetWindow<SimpleBindingPropertyExample>();
wnd.titleContent = new GUIContent("Simple Binding Property");
}
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");
// Bind the property to the field directly
m_ObjectNameBinding.BindProperty(property);
}
else
{
// Unbind any binding from the field
m_ObjectNameBinding.Unbind();
}
}
}
}