unity3d User Interface System (UI) Adding mouse listeners


Example

Sometimes, you want to add listeners on particular events not natively provided by the components, in particular mouse events. To do so, you will have to add them by yourself using an EventTrigger component :

using UnityEngine;
using UnityEngine.EventSystems;

[RequireComponent(typeof( EventTrigger ))]
public class CustomListenersExample : MonoBehaviour
{
    void Start( )
    {
        EventTrigger eventTrigger = GetComponent<EventTrigger>( );
        EventTrigger.Entry entry = new EventTrigger.Entry( );
        entry.eventID = EventTriggerType.PointerDown;
        entry.callback.AddListener( ( data ) => { OnPointerDownDelegate( (PointerEventData)data ); } );
        eventTrigger.triggers.Add( entry );
    }

    public void OnPointerDownDelegate( PointerEventData data )
    {
        Debug.Log( "OnPointerDownDelegate called." );
    }
}

Various eventID are possible :

  • PointerEnter
  • PointerExit
  • PointerDown
  • PointerUp
  • PointerClick
  • Drag
  • Drop
  • Scroll
  • UpdateSelected
  • Select
  • Deselect
  • Move
  • InitializePotentialDrag
  • BeginDrag
  • EndDrag
  • Submit
  • Cancel