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
Canvasis the root of any UI, everything inside it (buttons, images, text) is a child GameObject positioned in screen space, not world space. Screen Space - Overlaydraws 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'sOnClick()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.