버전: 2021.3+
이 예제는 C# 스크립트에서 바인딩 경로를 사용하여 바인딩하는 방법을 보여줍니다.
이 예제에서는 게임 오브젝트의 이름을 변경하는 커스텀 에디터 창을 생성합니다.
이 예시에서 만든 완성된 파일은 이 GitHub 저장소에서 찾을 수 있습니다.
이 가이드는 Unity 에디터, UI 툴킷, C# 스크립팅에 익숙한 개발자를 위한 가이드입니다. 시작하기 전에 먼저 다음을 숙지하십시오.
C#에서 TextField로 커스텀 에디터 창을 만들 수 있습니다. 바인딩 경로를 게임 오브젝트의 name 프로퍼티로 설정하고 Bind() 메서드를 명시적으로 호출합니다.
템플릿을 사용하여 Unity에서 프로젝트를 생성합니다.
프로젝트 창에서 파일을 저장할 bind-with-binding-path라는 폴더를 만듭니다.
bind-with-binding-path 폴더에 Editor라는 이름의 폴더를 만듭니다.
Editor 폴더에서 SimpleBindingExample.cs라는 이름의 C# 스크립트를 생성하고 해당 내용을 다음과 같이 바꿉니다.
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 = "";
}
}
}
}