Version: 6000.3
语言: 中文
在 C# 脚本中使用绑定路径绑定
使用 UXML 和 C# 脚本绑定

不带绑定路径的绑定

版本: 2021.3+

您可以调用BindProperty()将元素绑定到SerializedProperty对象,而不是绑定路径。此示例演示了如何与BindProperty().

示例概述

此示例创建一个自定义编辑器窗口,以更改游戏对象Unity 场景中的基本对象,可以表示角色、道具、风景、相机、航路点等。游戏对象的功能由附加到它的组件定义。更多信息
请参阅术语表
.

自定义 Unity 编辑器窗口,允许您更改游戏对象名称。
自定义 Unity 编辑器窗口,用于更改游戏对象的名称。

您可以在此 GitHub 存储库中找到此示例创建的已完成文件。

先决条件

本指南适用于熟悉 Unity 编辑器、UI 工具包和 C# 脚本的开发人员。在开始之前,请熟悉以下内容:

绑定为BindProperty()

在 C# 中使用 TextField 创建自定义编辑器窗口。查找游戏对象的 name 属性,并使用BindProperty()方法。

  1. 在您的项目窗口一个窗口,显示您的内容Assets文件夹(项目选项卡)更多信息
    术语表中查看
    ,创建一个名为bind-without-binding-path以存储您的文件。

  2. bind-without-binding-path 文件夹中,创建一个名为Editor.

  3. 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();
                }
            }
        }
    }
    

测试绑定

  1. 在 Unity 中,选择“窗口”>“UIToolkitExamples”>“简单绑定属性示例”。将出现一个带有文本字段的自定义编辑器窗口。
  2. 场景场景包含游戏的环境和菜单。将每个唯一的场景文件视为一个独特的关卡。在每个场景中,你放置你的环境、障碍物和装饰品,基本上是将你的游戏设计和构建成碎片。更多信息
    请参阅术语表
    .游戏对象的名称将显示在编辑器窗口的文本字段中。如果您在文本字段中更改游戏对象的名称,则游戏对象的名称也会更改。

其他资源

在 C# 脚本中使用绑定路径绑定
使用 UXML 和 C# 脚本绑定