unity3d Subscribing to event in code


Example

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 :