Wave Counter
Lesson 24 of 25 in Coddy's Unity Game: Tower Defense course.
The HUD shows the wave number. The spawner knows it, and the GameManager shows it, so the spawner raises a C# event, WaveStarted, with the wave and the number of waves. Unlike the enemies' static events, it belongs to the one spawner, and the GameManager subscribes through its spawner field:
void OnEnable()
{
spawner.WaveStarted += ShowWave;
}An Action<int, int> passes two ints, so ShowWave takes two: void ShowWave(int wave, int total).
Challenge
MediumShow which wave is on.
- In
WaveSpawner, addpublic event Action<int, int> WaveStarted;(using System;) and raise it withi + 1andwaves.Countas a wave starts. - In
GameManager, add serializedspawner(WaveSpawner) andwaveText(TMP_Text). Subscribe in OnEnable, unsubscribe in OnDisable, and showWave 1/8.
Press Play: Wave 1/8 shows at the top right as the first wave starts. Then Check.
Try it yourself
using UnityEngine;
using TMPro;
public class GameManager : MonoBehaviour
{
[SerializeField] private int startMoney = 150;
[SerializeField] private int startLives = 20;
[SerializeField] private TMP_Text moneyText;
[SerializeField] private TMP_Text livesText;
private int money;
private int lives;
void OnEnable()
{
Enemy.ReachedBase += OnReachedBase;
Enemy.Killed += OnKilled;
}
void OnDisable()
{
Enemy.ReachedBase -= OnReachedBase;
Enemy.Killed -= OnKilled;
}
void Start()
{
money = startMoney;
lives = startLives;
ShowMoney();
ShowLives();
}
public bool TrySpend(int amount)
{
if (amount > money)
{
return false;
}
money -= amount;
ShowMoney();
return true;
}
public void Earn(int amount)
{
money += amount;
ShowMoney();
}
void OnKilled(Enemy enemy)
{
Earn(enemy.data.reward);
}
void OnReachedBase(Enemy enemy)
{
lives -= enemy.data.damage;
ShowLives();
}
void ShowMoney()
{
moneyText.text = "Money: " + money;
}
void ShowLives()
{
livesText.text = "Lives: " + lives;
}
}
All lessons in Unity Game: Tower Defense
Practice on your own: Unity playground