NocabSoftware.com


Example of setting Unity Button onClick() funciton in code:

using UnityEngine;
using UnityEngine.UI;  // <-- This line is needed for access to the Button type

public class NocabOnClick : MonoBehaviour {

    public Button otherButton;
    public int number;

    void Start() {
        // This MonoBehaviour must be attached to an GameObject that already has a Button Component.
        // But the general technique still works on any Button Object
        Button myButton = this.GetComponent<Button>();

        myButton.onClick.AddListener(delegate { doWork(); });
        otherButton.onClick.AddListener(delegate { doWork(); });

        // Changing this.number variable will pass the new value into the function at the next click event
        myButton.onClick.AddListener(delegate { complexAction(number, false); });
    }
    

    private void doWork() {
        Debug.Log("Simple on click action");
    }

    private void complexAction(int n, bool b) {
        if (b) { Debug.Log("True work"); }
        else   { Debug.Log("False work"); }

        for(int i = 0; i < n; i++) {
            Debug.Log("Doing loop work: " + i);
        }
    }
}
  

Breif description:

A unity Button MonoBehavior allows for a single mouse click to run arbitrary code. This is ideal for most kinds of user interfaces because it can be computationally less intensive, compared to an if statement in the Update() function.

However, setting up Button MonoBehavior with the Unity editor is tedious, error prone and inflexable.

Setting up a Button via scripting is fairly easy. Using a script is also the easiest way to make a Unity Button onClick() function take arguments. These arguments can be constants hardcoded in, or variables that can be changed while the game is running.

More information and examples can be found on the Unity documentation.

A few gotchas: