요소의 값이 변경되면 ChangeEvent
가 전송됩니다. 보통 이 이벤트는 컨트롤의 필드 값이 변경되는 경우 전송됩니다(예: 사용자가 체크박스를 토글하는 경우).
ChangeEvent
는 타입이 부여된 이벤트로, 시각적 요소의 이전 값과 새 값을 모두 포함합니다.
이 이벤트는 변경이 시각적 요소에 새 값을 할당한 후 트리거됩니다. 시각적 요소의 값 변경을 막기 위해 변경 이벤트를 취소할 수는 없습니다.
ChangeEvent
의 베이스 클래스는 EventBase 클래스입니다.
이벤트 | 설명 | 트리클다운 | 버블업 | 취소 가능 |
---|---|---|---|---|
ChangeEvent | 요소의 값이 변경되면 전송되는 일반 이벤트. | ✔ | ✔ |
previousValue
: 타겟 컨트롤의 이전 값.
newValue
: 타겟 컨트롤의 새 값.
ChangeEvent
는 시각적 요소의 값 변경에 반응할 수 있게 하는 알림 이벤트입니다. 예를 들어, 게임의 음악을 음소거하기 위해 체크박스를 토글하면 게임이 모든 음악을 멈춰야 합니다.
이 이벤트는 INotifyValueChanged<T>
를 구현하는 모든 컨트롤에 적용되며, 여기서 <T>
는 ChangeEvent
의 타입입니다. 또한 이 이벤트는 바인딩을 통해 UI에 연결된 오브젝트 내 프로퍼티를 업데이트하는 데 내부적으로 사용됩니다.
이 이벤트는 컨트롤의 값이 코드에 의해 설정된 경우에도 실행됩니다. INotifyValueChange<T>
인터페이스에서 SetValueWithoutNotify
를 호출하여 ChangeEvent
를 실행하지 않고도 컨트롤의 값을 수정할 수 있습니다.
다음 두 가지 방법으로 콜백 함수를 등록하여 ChangeEvent
를 받을 수 있습니다.
RegisterCallback<>()
호출INotifyValueChange<T>
에서 파생된 시각적 요소에서 RegisterValueChangedCallback()
호출시각적 요소에 내부 값이 저장되어 있는지 여부와 관계없이 모든 시각적 요소에서 RegisterCallback을 통해 콜백을 등록할 수 있습니다. 부모 요소의 자식 컨트롤에서 발생하는 모든 변경 사항을 파악하려면 이 메서드를 사용하십시오.
ChangeEvent
는 타입이 부여된 이벤트이므로, 이벤트를 등록할 때 타입을 지정해야 합니다. 아래 코드는 bool
타입의 ChangeEvent
를 등록하고 받는 방법을 나타냅니다.
// Registering the callback
rootVisualElement.RegisterCallback<ChangeEvent<bool>>(OnBoolChangedEvent);
// Event callback
private void OnBoolChangedEvent(ChangeEvent<bool> evt)
{
// Handling code
}
토글과 정수 필드와 같은 값을 포함하는 요소는 INotifyValueChange<T>
인터페이스를 구현합니다. RegisterValueChangedCallback을 호출하여 이러한 요소에 직접 콜백을 등록할 수 있습니다. 타입이 이미 빌트인되어 있으므로, 이 방법을 사용하면 콜백을 보다 편리하게 등록할 수 있습니다. myElement.UnregisterValueChangedCallback
을 호출하면 이벤트 핸들러를 다시 등록 취소할 수 있습니다.
var newToggle = new Toggle("Test Toggle");
newToggle.RegisterValueChangedCallback(OnTestToggleChanged);
private void OnTestToggleChanged(ChangeEvent<bool> evt)
{
// Handling code
}
target
: 상태 변경이 발생한 요소입니다.
다음 예제는 ChangeEvent
의 사용 및 컨트롤 값을 설정하고 받는 방법을 나타냅니다.
예제의 동작을 확인하려면 다음 단계를 따르십시오.
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
public class ChangeEventTestWindow : EditorWindow
{
private Toggle m_MyToggle;
[MenuItem("Window/UI Toolkit/Change Event Test Window")]
public static void ShowExample()
{
ChangeEventTestWindow wnd = GetWindow<ChangeEventTestWindow>();
wnd.titleContent = new GUIContent("Change Event Test Window");
}
public void CreateGUI()
{
// Create a toggle
m_MyToggle = new Toggle("Test Toggle") { name = "My Toggle" };
rootVisualElement.Add(m_MyToggle);
// Register a callback on the toggle
m_MyToggle.RegisterValueChangedCallback(OnTestToggleChanged);
// Register a callback on the parent
rootVisualElement.RegisterCallback<ChangeEvent<bool>>(OnBoolChangedEvent);
}
private void OnBoolChangedEvent(ChangeEvent<bool> evt)
{
Debug.Log($"Toggle changed. Old value: {evt.previousValue}, new value: {evt.newValue}");
}
private void OnTestToggleChanged(ChangeEvent<bool> evt)
{
Debug.Log($"A bool value changed. Old value: {evt.previousValue}, new value: {evt.newValue}");
}
}
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
public class ChangeEventTestWindow : EditorWindow
{
private Toggle m_MyToggle;
[MenuItem("Window/UI Toolkit/Change Event Test Window")]
public static void ShowExample()
{
GetWindow<ChangeEventTestWindow>().titleContent = new GUIContent("Change Event Test Window");
}
public void CreateGUI()
{
// Create a toggle and register callback
m_MyToggle = new Toggle("Test Toggle") { name = "My Toggle" };
m_MyToggle.RegisterValueChangedCallback((evt) => { Debug.Log("Change Event received"); });
rootVisualElement.Add(m_MyToggle);
// Create button to toggle the toggle's value
Button button01 = new Button() { text = "Toggle" };
button01.clicked += () =>
{
m_MyToggle.value = !m_MyToggle.value;
};
rootVisualElement.Add(button01);
// Create button to toggle the toggle's value without triggering a ChangeEvent
Button button02 = new Button() { text = "Toggle without notification" };
button02.clicked += () =>
{
m_MyToggle.SetValueWithoutNotify(!m_MyToggle.value);
};
rootVisualElement.Add(button02);
}
}
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.