Make It Yours
Lesson 25 of 25 in Coddy's Unity Game: Tower Defense course.
The game needs its ending. It is lost when the lives reach 0, and won when every wave has been sent and no enemy is left. The spawner waits for an empty board with WaitUntil, which checks a lambda once per frame, then raises an event:
yield return new WaitUntil(() => switchesOn == switches.Length);Either ending shows the EndPanel and stops the game with Time.timeScale = 0. A Tank that takes 2 when 1 life is left would skip past a check for exactly 0, so Mathf.Max keeps the lives at 0 or more. Time.timeScale keeps its value through a scene load, so Play Again sets it back to 1 first.
Then make the game yours. Here startMoney (150), startLives (20) and timeBetweenWaves (8) take the values in your code, since this player's Inspector is read only: change them where they are declared and press Play. A mixed defense in the bends of the path, upgraded as the money comes in, beats the default game.
Challenge
HardEnd the game, then tune it in your code.
WaveSpawner: addpublic event Action AllWavesCleared;, raised after the last wave onceEnemy.All.Count == 0(WaitUntil).GameManager: keep lives at 0 or more.End(message)shows serializedendPanelandendTextand setsTime.timeScale = 0:Game Overat 0 lives,You Win!when all waves are cleared.public void PlayAgain():Time.timeScale = 1, then reload the scene.
Press Play and defend the base through all eight waves. 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 WaveSpawner spawner;
[SerializeField] private TMP_Text moneyText;
[SerializeField] private TMP_Text livesText;
[SerializeField] private TMP_Text waveText;
private int money;
private int lives;
void OnEnable()
{
Enemy.ReachedBase += OnReachedBase;
Enemy.Killed += OnKilled;
spawner.WaveStarted += ShowWave;
}
void OnDisable()
{
Enemy.ReachedBase -= OnReachedBase;
Enemy.Killed -= OnKilled;
spawner.WaveStarted -= ShowWave;
}
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;
}
void ShowWave(int wave, int total)
{
waveText.text = "Wave " + wave + "/" + total;
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Game: Tower Defense
Practice on your own: Unity playground