바인딩
프로퍼티와 해당 프로퍼티를 수정하는 시각 컨트롤 간의 연결을 의미
목적
오브젝트 내 프로퍼티를 표시되는 UI와 동기화하는 것
바인딩은 오브젝트, 그리고 BindableElement에서 파생되거나 IBindable 인터페이스를 구현하는 UIElement간에 이루어진다. 여기서 UIElement는 우리가 사용할 수 있는 UI 컴포넌트들을 말한다.
C#을 사용한 바인딩
다음 코드 스니핏은 C# 코드로 바인딩을 생성하는 방법이다.
using UnityEditor;
using UnityEngine;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace UIElementsExamples
{
public class SimpleBindingExample : EditorWindow
{
TextField m_ObjectNameBinding;
[MenuItem("Window/UIElementsExamples/Simple Binding Example")]
public static void ShowDefaultWindow()
{
var wnd = GetWindow<SimpleBindingExample>();
wnd.titleContent = new GUIContent("Simple Binding");
}
public void OnEnable()
{
var root = this.rootVisualElement;
m_ObjectNameBinding = new TextField("Object Name Binding");
m_ObjectNameBinding.bindingPath = "m_Name";
root.Add(m_ObjectNameBinding);
OnSelectionChange();
}
public void OnSelectionChange()
{
GameObject selectedObject = Selection.activeObject as GameObject;
if (selectedObject != null)
{
// Create serialization object
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);
// ... or alternatively you can also bind it to the TextField itself.
// m_ObjectNameBinding.Bind(so);
}
else
{
// Unbind the object from the actual visual element
rootVisualElement.Unbind();
// m_ObjectNameBinding.Unbind();
// Clear the TextField after the binding is removed
m_ObjectNameBinding.value = "";
}
}
}
}
이 방법을 따르면 윈도우 창에서 윈도우 모드를 통해 원하는 오브젝트에 TextField 컴포넌트를 추가할 수 있게 된다. 스크립트 내에서 Text가 아닌 image나 button click event 등으로 변경한다면 우리는 원할 때 원하는 오브젝트에 필요한 컴포넌트를 지정해서 붙일 수 있게 된다.
그럼 이것을 어느 상황에서 쓸 수 있을까?
게임에는 수 많은 팝업 UI가 사용된다. 이것을 씬마다 만들어주고 쓴다면 기본적으로 씬이 로딩되는 시간이 오래 걸리고 여러 씬에서 사용되는 HUD는 중복될 수 있다. 그래서 우리는 필요할 때마다 꺼내 쓸 수 있거나 프리팹으로 만들어 불러올 수 있도록 해야한다. 그럴 때 이 Bind 함수를 유용하게 사용 가능하다.
'Unity > TIL' 카테고리의 다른 글
[최종 프로젝트] 게임 기획 (0) | 2024.07.11 |
---|---|
Unity Extension Method / 확장 메서드 (0) | 2024.07.05 |
[면접대비] 객체와 한정자 (0) | 2024.07.01 |
피드백에 대한 수정 및 공부 (0) | 2024.06.26 |
Unity photon 멀티플레이 예외처리 (0) | 2024.06.24 |