Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 36 ยท UI and Input

Buttons, Text and UI Events in Unity

Wire up Unity buttons, sliders, toggles and TextMeshPro text from code, learn UnityEvent listeners, the EventSystem and common mistakes, with runnable C# event stand-ins.

A Canvas is only a surface. The things players touch are UI controls: buttons, sliders, toggles, input fields and dropdowns, plus text and images that show information. This lesson shows how to create them, how to react to them in C#, and how Unity's event system delivers a click to the right script.

As in the previous lesson, the Unity API code is read-only and the runnable blocks are plain C# stand-ins for the mechanisms (events, listeners, a score display) so you can experiment without the editor.

Text with TextMeshPro

Use TextMeshPro (TMP) for all text. Create it with GameObject > UI > Text - TextMeshPro. It renders crisp text at any size using signed distance fields and supports rich text such as <color=red>Low!</color> and <b>bold</b>.

C#
using TMPro;
using UnityEngine;

public class ScoreLabel : MonoBehaviour
{
    [SerializeField] TextMeshProUGUI label;
    int score;

    public void Add(int points)
    {
        score += points;
        label.text = $"Score: {score:N0}";
    }
}

Drag the TMP object into the label slot in the Inspector. Setting text every frame creates garbage; update it only when the value changes. For a live-updating number use SetText("{0}", value), which avoids allocating a string.

Buttons and onClick

A Button has an On Click () list in the Inspector, and an onClick event you can use from code:

C#
using UnityEngine;
using UnityEngine.UI;

public class MainMenu : MonoBehaviour
{
    [SerializeField] Button playButton;
    [SerializeField] Button quitButton;

    void OnEnable()
    {
        playButton.onClick.AddListener(OnPlay);
        quitButton.onClick.AddListener(OnQuit);
    }

    void OnDisable()
    {
        playButton.onClick.RemoveListener(OnPlay);
        quitButton.onClick.RemoveListener(OnQuit);
    }

    void OnPlay() => UnityEngine.SceneManagement.SceneManager.LoadScene("Game");
    void OnQuit() => Application.Quit();
}

Always remove listeners you add (in OnDisable or OnDestroy); a leaked listener keeps a destroyed object alive or runs twice. A lambda is fine for a one-off, but you cannot remove it later unless you store it in a variable.

Buttons have a Transition setting: Color Tint (normal, highlighted, pressed, selected, disabled colors), Sprite Swap or Animation. button.interactable = false greys out a button and stops clicks.

UnityEvent: events you can see in the Inspector

onClick is a UnityEvent, a delegate list that can also be filled in the Inspector. You can declare your own:

C#
using UnityEngine;
using UnityEngine.Events;

public class Health : MonoBehaviour
{
    public UnityEvent<int> onChanged;   // shows up in the Inspector
    public UnityEvent onDied;
    int hp = 100;

    public void Damage(int amount)
    {
        hp = Mathf.Max(0, hp - amount);
        onChanged.Invoke(hp);
        if (hp == 0) onDied.Invoke();
    }
}

Designers can then connect onChanged to a health bar's SetValue and onDied to a "Game Over" panel without touching code. For pure code-to-code communication, plain C# event Action<int> is lighter and faster; the stand-in below shows both ideas.

C# Stand-in: events and listeners

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Sliders, toggles, inputs and dropdowns

Each control exposes one event, all following the same pattern:

Control Event Value
Slider onValueChanged(float) value, between minValue and maxValue
Toggle onValueChanged(bool) isOn
TMP_InputField onValueChanged(string), onEndEdit(string) text
TMP_Dropdown onValueChanged(int) value (option index)

A settings menu is usually a handful of these. Be careful: setting slider.value from code also raises onValueChanged. Use SetValueWithoutNotify(x) when you load saved settings so you do not trigger saving again.

C# Stand-in: a volume slider that clamps and notifies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The conversion to decibels matters: audio mixers use dB, and 0.0001 stands for "silent" because log10(0) is minus infinity. You will use exactly this in Audio sources and the mixer.

How a click finds its button

The EventSystem polls an Input Module every frame. A Graphic Raycaster on each Canvas tests the pointer position against every UI element that has Raycast Target enabled, and the topmost hit receives the event. Consequences:

  • No EventSystem in the scene means no clicks. (Creating a Canvas adds one; deleting it breaks the UI.)
  • A transparent full-screen Image with Raycast Target on will block everything beneath it. Turn Raycast Target off for decorative images and text.
  • To detect whether the pointer is over the UI before firing a weapon, call EventSystem.current.IsPointerOverGameObject().
  • Implement IPointerClickHandler, IPointerEnterHandler, IDragHandler and friends on your own script to react to events that Button does not expose.

Common mistakes

  • Forgetting to assign a serialized field, then getting a NullReferenceException at the first click. Check the Inspector slots.
  • Using the legacy UnityEngine.UI.Text instead of TextMeshPro.
  • Wiring a button in the Inspector to a method on a prefab asset instead of the scene instance.
  • Disabling the Canvas Scaler's raycasts by mistake, or having two EventSystems in the scene (Unity warns).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What should you do with listeners you add with onClick.AddListener?

    Unremoved listeners can run twice after re-enabling or keep destroyed objects referenced.
  2. 2. Which method changes a slider's value without raising onValueChanged?

    SetValueWithoutNotify updates the value silently, which is ideal when restoring saved settings.
  3. 3. A transparent Image covers the screen and nothing underneath responds to clicks. What is the likely cause?

    The Graphic Raycaster gives the event to the topmost raycast-target element, so an invisible one blocks the rest.
  4. 4. Why use SetText("{0}", value) on a TMP label that updates often?

    String building creates garbage that triggers garbage collection; SetText formats into an internal buffer.

Summary

  • Use TextMeshPro for text and update it only when the value changes.
  • Buttons and other controls expose UnityEvents (onClick, onValueChanged); add and remove listeners symmetrically.
  • UnityEvent is Inspector-friendly; plain C# events are lighter for code-only links.
  • The EventSystem and Graphic Raycaster route input; Raycast Target on invisible graphics blocks clicks.
  • SetValueWithoutNotify avoids feedback loops when loading settings.

Next: The Input System