Unity3D :使用 C# 脚本中的绑定路径进行绑定
推荐:将NSDT场景编辑器加入你的3D工具链
3D工具集:NSDT简石数字孪生
使用 C# 脚本中的绑定路径进行绑定
此示例演示如何使用 C# 脚本中的绑定路径进行绑定。
示例概述
此示例创建一个自定义编辑器窗口以更改游戏对象
.
您可以在此 GitHub 存储库中找到此示例创建的已完成文件。
先决条件
本指南适用于熟悉 Unity 编辑器的开发人员,用户界面
工具包和 C# 脚本。在开始之前,请熟悉以下内容:
bindingPath
Bind()
使用绑定路径绑定
在 C# 中创建一个自定义编辑器窗口,其中包含 .将绑定路径设置为游戏对象的 name 属性,并对该方法进行显式调用。TextFieldBind()
- 使用任何模板在 Unity 中创建项目。
- 在你的项目窗口
,创建一个名为文件夹的文件夹来存储您的文件。bind-with-binding-path
- 在绑定与绑定路径文件夹中,创建一个名为 的文件夹。
Editor
在“编辑器”文件夹中,创建一个名为的 C# 脚本,并将其内容替换为以下内容: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 = "";
}
}
}
}
测试绑定
- 在 Unity 中,选择“> UIToolkit示例”>“简单绑定示例”窗口。此时将显示一个带有文本字段的自定义编辑器窗口。
- 选择您的任何游戏对象现场
.游戏对象的名称将显示在编辑器窗口的文本字段中。如果在文本字段中更改游戏对象的名称,则游戏对象的名称也会更改。
由3D建模学习工作室整理翻译,转载请注明出处!