包含此页的版本:
不含此页的版本:
版本: 2021.3+
您可以调用BindProperty()将元素绑定到SerializedProperty对象,而不是绑定路径。此示例演示了如何与BindProperty().
此示例创建一个自定义编辑器窗口,以更改游戏对象Unity 场景中的基本对象,可以表示角色、道具、风景、相机、航路点等。游戏对象的功能由附加到它的组件定义。更多信息
请参阅术语表.
您可以在此 GitHub 存储库中找到此示例创建的已完成文件。
本指南适用于熟悉 Unity 编辑器、UI 工具包和 C# 脚本的开发人员。在开始之前,请熟悉以下内容:
BindProperty()
在 C# 中使用 TextField 创建自定义编辑器窗口。查找游戏对象的 name 属性,并使用BindProperty()方法。
在您的项目窗口一个窗口,显示您的内容Assets文件夹(项目选项卡)更多信息
在术语表中查看,创建一个名为bind-without-binding-path以存储您的文件。
在 bind-without-binding-path 文件夹中,创建一个名为Editor.
在 Editor 文件夹中,创建一个名为SimpleBindingPropertyExample.cs并将其内容替换为以下内容:
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();
}
}
}
}