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
EasyMake the lift's Up and Down buttons work.
- In
Start(), hookupButtontoGoUp(floor++) anddownButtontoGoDown(floor--) withonClick.AddListener. - Write
ShowFloor(), called inStart()and after each move: the lift's y isfloor * floorHeight, andfloorTextreadsFloor: 2. - 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
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input SwapPractice on your own: Unity playground