Menu
CoddyTech

Buttons and onClick

Part of the Building Real Games section of Coddy's Unity journey. Lesson 6 of 60.

GameObject > UI > Button - TextMeshPro adds a button: an Image to click, a Button component, and a Text (TMP) child for its label. The Button's onClick is an event, a list of methods it calls when a click is released over it. A script adds its own method to that list with AddListener, once, in Start(). Button lives in the UnityEngine.UI namespace:

using UnityEngine;
using UnityEngine.UI;

public class Doorbell : MonoBehaviour
{
    public Button bellButton;
    private int rings;

    void Start()
    {
        bellButton.onClick.AddListener(Ring);
    }

    void Ring()
    {
        rings++;
        Debug.Log("Ding! " + rings);
    }
}

AddListener(Ring) passes the method itself, without parentheses. AddListener(Ring()) would call Ring at once and pass what it returns, which is nothing, so it does not compile: Argument 1: cannot convert from 'void' to 'UnityEngine.Events.UnityAction'. A listener takes no parameters and returns void. Added in Update(), the same method would join the list again every frame, and one click would ring hundreds of times. A click counts only on the button itself, while Input.GetMouseButtonDown(0) is true for a click anywhere.

A button's interactable decides whether it can be used. bellButton.interactable = false; tints it with its Disabled Color and its listeners are not called until it is set back to true, so the player sees which buttons work right now. On a phone, the same buttons are tapped.

challenge icon

Challenge

Easy

Make the lift's Up and Down buttons work.

  1. In Start(), hook upButton to GoUp (floor++) and downButton to GoDown (floor--) with onClick.AddListener.
  2. Write ShowFloor(), called in Start() and after each move: the lift's y is floor * floorHeight, and floorText reads Floor: 2.
  3. Up is interactable below topFloor, Down above 0.

Press Play: Up greys out at the top. Then Check.

Try it yourself

using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class Lift : MonoBehaviour
{
    public Button upButton;
    public Button downButton;
    public TMP_Text floorText;
    public int topFloor = 3;
    public float floorHeight = 3f;
    private int floor;

    void Start()
    {
        // Hook upButton and downButton to methods that move the lift one floor
    }
}

All lessons in Building Real Games

Practice on your own: Unity playground