Skip to content

6. Event interfaces

Joni Savolainen edited this page Dec 9, 2022 · 4 revisions

Creating event interfaces

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...
    }
}

Built-in event interfaces

Below are the event interfaces built-in to UIComponents.

IOnAttachToPanel for AttachToPanelEvent

public partial class ComponentWithCallbacks : UIComponent, IOnAttachToPanel
{
    public void OnAttachToPanel(AttachToPanelEvent evt)
    {
        Debug.Log("Hello world");
    }
}

IOnDetachFromPanel for DetachFromPanelEvent

public partial class ComponentWithCallbacks : UIComponent, IOnDetachFromPanel
{
    public void OnDetachFromPanel(DetachFromPanelEvent evt)
    {
        Debug.Log("Goodbye world");
    }
}

IOnGeometryChanged for GeometryChangedEvent

public partial class ComponentWithCallbacks : UIComponent, IOnGeometryChanged
{
    public void OnGeometryChanged(GeometryChangedEvent evt)
    {
        Debug.Log("Geometry changed");
        UnregisterCallback<GeometryChangedEvent>(OnGeometryChanged);
    }
}

IOnMouseEnter for MouseEnterEvent

public partial class ComponentWithCallbacks : UIComponent, IOnMouseEnter
{
    public void OnMouseEnter(MouseEnterEvent evt)
    {
        Debug.Log("Hi mouse");
    }
}

IOnMouseLeave for MouseLeaveEvent

public partial class ComponentWithCallbacks : UIComponent, IOnMouseLeave
{
    public void OnMouseLeave(MouseLeaveEvent evt)
    {
        Debug.Log("Bye mouse");
    }
}

IOnClick for ClickEvent

public partial class ComponentWithCallbacks : UIComponent, IOnClick
{
    public void OnClick(ClickEvent evt)
    {
        Debug.Log("Clicked!");
    }
}

IOnNavigationMove for NavigationMoveEvent (requires Unity 2021+)

public partial class ComponentWithCallbacks : UIComponent, IOnNavigationMove
{
    public void OnNavigationMove(NavigationMoveEvent evt)
    {
        Debug.Log("We navigated!");
    }
}