I’ve recently been playing with Unity quite a bit and got stuck on how to add event listeners to buttons that I made in the visual designer programatically and not through the ui interface. This Code adds an onClick event to any button in the scene, and if any of them are clicked the method ButtonClick is called with the button as a paramater.

In my opinion, this is much nicer than using the messy graphical interface to set it up, and also keeps all the logic in the main game class.

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class GameCode: MonoBehaviour
{
   void Start ()
   {
      var allUIElements = UnityEngine.UI.Button.allSelectables.ToArray ();
      foreach (var uiItem in allUIElements)
      {
         if(uiItem.GetType() == (typeof(Button)))
         {
            Button uiButton = (Button) uiItem;
            uiButton.onClick.RemoveAllListeners();
            uiButton.onClick.AddListener(() => ButtonClick(uiButton));
         }
      }
   }

   public void ButtonClick(Button clickedButton)
   {
      Debug.Log ("clicked: " + clickedButton.name);
     }
   }
}