Wiring in the Inspector
Part of the Building Real Games section of Coddy's Unity journey. Lesson 8 of 56.
A button can also be wired in the Inspector, with no AddListener at all. The Button's On Click () list starts empty. Its + adds a row; drag the object that holds the script into the row's object slot, and the function dropdown lists that object's components, each with its public methods. Pick Jukebox > NextTrack, and every click calls this method:
public class Jukebox : MonoBehaviour
{
public string[] tracks;
private int current;
public void NextTrack()
{
current = (current + 1) % tracks.Length;
Debug.Log("Now playing: " + tracks[current]);
}
}The dropdown lists methods that are public, return void, and take no parameter or one int, float, string, bool or Object, whose value you set in the row. A private NextTrack is not listed, so it cannot be picked. The row stores the method by its name: rename NextTrack to SkipTrack and the row shows <Missing Jukebox.NextTrack>, and clicks do nothing, with no error in the Console.
Rows in the Inspector suit buttons placed in the scene: anyone on the team can see and change what a button calls without opening a script. AddListener in code suits buttons created while the game runs and calls that pass a value from a variable, and the compiler catches a renamed method there. Listeners added from code never appear in the On Click () list, so a button wired both ways calls both.
Challenge
EasyThe castle's drawbridge has three buttons, wired in the Inspector to the Drawbridge script on BridgeControl. None of them works yet. Select RaiseButton, LowerButton and LampButton in the Hierarchy and read each On Click () row: it names the method the click calls. Make all three work by changing Drawbridge.cs only:
- One of the methods is already written, under another name. Give it the name its row calls.
- Raising turns
bridgeto 70 degrees around x (itslocalRotation) and showsBridge: upinstatusText. - The lamp button switches
warningLampon when it is off, and off when it is on.
Press Play, try every button, then Check.
Try it yourself
using UnityEngine;
using TMPro;
public class Drawbridge : MonoBehaviour
{
public Transform bridge;
public TMP_Text statusText;
public GameObject warningLamp;
public void LowerBridge()
{
bridge.localRotation = Quaternion.Euler(0f, 0f, 0f);
statusText.text = "Bridge: down";
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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 Swap