Menu
CoddyTech

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 icon

Challenge

Easy

Make the drawbridge's three buttons work in Drawbridge.cs.

  1. Each button's On Click () row calls Raise, Lower or ToggleLamp. Rename LowerBridge to Lower.
  2. Write public void Raise(): bridge.localRotation turns to 70 degrees around x, and statusText reads Bridge: up.
  3. Write public void ToggleLamp(): it switches warningLamp on 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

Practice on your own: Unity playground