包含此页的版本:
不含此页的版本:
版本: 2021.3+
此示例演示如何在 C# 脚本中绑定绑定路径。
此示例创建一个自定义编辑器窗口,以更改游戏对象Unity 场景中的基本对象,可以表示角色、道具、风景、相机、航路点等。游戏对象的功能由附加到它的组件定义。更多信息
请参阅术语表.
您可以在此 GitHub 存储库中找到此示例创建的已完成文件。
本指南适用于熟悉 Unity 编辑器、UI 工具包和 C# 脚本的开发人员。在开始之前,请熟悉以下内容:
在 C# 中使用TextField.将绑定路径设置为游戏对象的 name 属性,并显式调用Bind()方法。
使用任何模板在 Unity 中创建项目。
在您的项目窗口一个窗口,显示您的内容Assets文件夹(项目选项卡)更多信息
在术语表中查看,创建一个名为bind-with-binding-path文件夹来存储您的文件。
在bind-with-binding-path文件夹中,创建一个名为Editor.
在 Editor 文件夹中,创建一个名为SimpleBindingExample.cs并将其内容替换为以下内容:
using UnityEditor;
using UnityEngine;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace UIToolkitExamples
{
public class SimpleBindingExample : EditorWindow
{
TextField m_ObjectNameBinding;
[MenuItem("Window/UIToolkitExamples/Simple Binding Example")]
public static void ShowDefaultWindow()
{
var wnd = GetWindow<SimpleBindingExample>();
wnd.titleContent = new GUIContent("Simple Binding");
}
public void CreateGUI()
{
m_ObjectNameBinding = new TextField("Object Name Binding");
// Note: the "name" property of a GameObject is "m_Name" in serialization.
m_ObjectNameBinding.bindingPath = "m_Name";
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);
// Bind it to the root of the hierarchy. It will find the right object to bind to.
rootVisualElement.Bind(so);
// Alternatively you can instead bind it to the TextField itself.
// m_ObjectNameBinding.Bind(so);
}
else
{
// Unbind the object from the actual visual element that was bound.
rootVisualElement.Unbind();
// If you bound the TextField itself, you'd do this instead:
// m_ObjectNameBinding.Unbind();
// Clear the TextField after the binding is removed
m_ObjectNameBinding.value = "";
}
}
}
}