Reach the Base
Lesson 3 of 25 in Coddy's Unity Game: Tower Defense course.
An enemy on the last waypoint has reached the base: it goes, and the base loses lives. The lives belong to the GameManager. Soon the enemies are made from prefabs, and a prefab cannot point at the GameManager in the scene, so the enemy reports with a static event. It belongs to the Enemy class, so the GameManager subscribes once and hears every enemy, also ones made later. The enemy raises it with ReachedBase?.Invoke(this);: the ? skips it when no one listens, and this tells the listener which kind got through.
void OnEnable()
{
Enemy.ReachedBase += OnReachedBase;
}
void OnDisable()
{
Enemy.ReachedBase -= OnReachedBase;
}A static event lives as long as the game, so each += needs its -=: a destroyed GameManager that never left would still be called.
Challenge
EasyEnemies that reach the base cost lives.
- In
EnemyData, addpublic int damage;. - In
Enemy, addpublic static event Action<Enemy> ReachedBase;(using System;). On the last waypoint, raise it and destroy the enemy. - In
GameManager, add[SerializeField] private int startLives = 20;andprivate int lives;, set in Start. Subscribe as above;OnReachedBasetakesenemy.data.damageoff the lives.
Press Play: both enemies vanish at the base. Then Check.
Try it yourself
using UnityEngine;
// Comes later: lives, money, the HUD, winning and losing.
public class GameManager : MonoBehaviour
{
}
All lessons in Unity Game: Tower Defense
Practice on your own: Unity playground