Menu
CoddyTech

The HUD

Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 46 of 50.

challenge icon

Challenge

Medium

A HUD that only listens. Keep everything from the earlier lessons. The canvas, named HUD, has a health bar (HealthFill, a Filled image), HealthText and WaveText, and your HUD script, with hero, spawner, healthBar, healthText and waveText set in the Inspector. The HUD never asks the hero or the spawner anything: they announce their changes with C# events, and the HUD shows what it hears.

  • Hero gets public event Action<int, int> HealthChanged, raised with the health and maxHealth in Start, and whenever a hit or a heal changes the health.
  • WaveSpawner gets public event Action<int> WaveStarted, raised with the wave's number when a wave starts.
  • HUD subscribes to both in OnEnable and unsubscribes in OnDisable. On HealthChanged it fills the bar to the share of health left and shows the health as HP 3/5. On WaveStarted it shows Wave 2. It has no Update.

Raise HealthChanged in Start, not in Awake: every object's OnEnable runs before any Start, so by then the HUD is listening. Press Play and watch the HUD while you fight, then Check.

Try it yourself

using UnityEngine;

public class HUD : MonoBehaviour
{
    // A later lesson fills this in: health and wave on screen.
}

All lessons in Game Architecture in Unity