-
Notifications
You must be signed in to change notification settings - Fork 9
6. Event interfaces
Joni Savolainen edited this page Dec 9, 2022
·
4 revisions
UIComponents supports the creation of "event interfaces". When a component implements them, code will be automatically generated for registering and unregistering callbacks.
using UnityEngine.UIElements;
using UIComponents.InterfaceModifiers;
namespace MyLibrary
{
public class MyEvent : EventBase<MyEvent> {}
[RegistersEventCallback(typeof(MyEvent))]
public interface IOnMyEvent
{
void OnMyEvent(MyEvent evt);
}
}
The registered interface method is automatically determined by simply removing the leading "I" from
the interface name. Alternatively, the method name can be passed as an argument to RegistersEventCallbackAttribute
.
[RegistersEventCallback(typeof(MyEvent), "OnEventTrigger")]
public interface IOnMyEvent
{
void OnEventTrigger(MyEvent evt);
}
To use the interface, simply implement it.
public partial class MyEventComponent : UIComponent, IOnMyEvent
{
// This method will be registered as a callback for MyEvent for you.
public void OnMyEvent(MyEvent evt)
{
// code here...
}
}
Below are the event interfaces built-in to UIComponents.
public partial class ComponentWithCallbacks : UIComponent, IOnAttachToPanel
{
public void OnAttachToPanel(AttachToPanelEvent evt)
{
Debug.Log("Hello world");
}
}
public partial class ComponentWithCallbacks : UIComponent, IOnDetachFromPanel
{
public void OnDetachFromPanel(DetachFromPanelEvent evt)
{
Debug.Log("Goodbye world");
}
}
public partial class ComponentWithCallbacks : UIComponent, IOnGeometryChanged
{
public void OnGeometryChanged(GeometryChangedEvent evt)
{
Debug.Log("Geometry changed");
UnregisterCallback<GeometryChangedEvent>(OnGeometryChanged);
}
}
public partial class ComponentWithCallbacks : UIComponent, IOnMouseEnter
{
public void OnMouseEnter(MouseEnterEvent evt)
{
Debug.Log("Hi mouse");
}
}
public partial class ComponentWithCallbacks : UIComponent, IOnMouseLeave
{
public void OnMouseLeave(MouseLeaveEvent evt)
{
Debug.Log("Bye mouse");
}
}
public partial class ComponentWithCallbacks : UIComponent, IOnClick
{
public void OnClick(ClickEvent evt)
{
Debug.Log("Clicked!");
}
}
public partial class ComponentWithCallbacks : UIComponent, IOnNavigationMove
{
public void OnNavigationMove(NavigationMoveEvent evt)
{
Debug.Log("We navigated!");
}
}