The HUD
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 46 of 50.
Challenge
MediumA 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.
Herogetspublic event Action<int, int> HealthChanged, raised with the health andmaxHealthinStart, and whenever a hit or a heal changes the health.WaveSpawnergetspublic event Action<int> WaveStarted, raised with the wave's number when a wave starts.HUDsubscribes to both inOnEnableand unsubscribes inOnDisable. OnHealthChangedit fills the bar to the share of health left and shows the health asHP 3/5. OnWaveStartedit showsWave 2. It has noUpdate.
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
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular Turret10Project: Arena Survivor
The HeroEnemy Types