By default, one should subscribe to event using inspector, but sometimes it's better to do it in code. In this example we subscribe to click event of a button in order to handle it.
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Button))]
public class AutomaticClickHandler : MonoBehaviour
{
private void Awake()
{
var button = this.GetComponent<Button>();
button.onClick.AddListener(HandleClick);
}
private void HandleClick()
{
Debug.Log("AutomaticClickHandler.HandleClick()", this);
}
}
The UI components usually provide their main listener easily :
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 :