Wiring in the Inspector
Part of the Building Real Games section of Coddy's Unity journey. Lesson 8 of 60.
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
EasyMake the drawbridge's three buttons work in Drawbridge.cs.
- Each button's On Click () row calls
Raise,LowerorToggleLamp. RenameLowerBridgetoLower. - Write
public void Raise():bridge.localRotationturns to 70 degrees around x, andstatusTextreadsBridge: up. - Write
public void ToggleLamp(): it switcheswarningLampon when it is off, and off when on.
Press Play: every button does its job. 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";
}
}
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