Unity Essentials: Physics, UI & Gameplay Systems

Lesson 3 of 8

The UI System: Canvas and UGUI

Unity's built-in UI system (UGUI) renders every on-screen element, buttons, health bars, menus, inside a Canvas.

using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class HealthBar : MonoBehaviour
{
    public Slider slider;
    public TMP_Text label;

    public void SetHealth(int current, int max)
    {
        slider.value = (float)current / max;
        label.text = $"{current} / {max}";
    }
}

The pieces

  • A Canvas is the root of any UI, everything inside it (buttons, images, text) is a child GameObject positioned in screen space, not world space.
  • Screen Space - Overlay draws the UI on top of everything, always facing the camera, most common for HUDs and menus.
  • Wiring a button click to code: select the Button's OnClick() list in the Inspector, drag in the target GameObject, and pick a public method, or do it from code:
button.onClick.AddListener(() => Debug.Log("Clicked!"));

Data binding in practice

UI elements don't update themselves, your code has to push new values to them, like calling SetHealth from a health-changed callback whenever health changes. Keep UI update code in dedicated UI scripts (like HealthBar above) rather than scattering slider.value = ... across gameplay code, that separation makes both sides easier to change independently.

📝 UI System Quiz

Passing score: 70%
  1. 1.What GameObject must every UGUI element live under?

  2. 2.button.onClick.____(() => ...) wires up a click handler from code.

  3. 3.UI elements like a Slider automatically update themselves whenever a related gameplay value changes, with no code needed.