Menu
CoddyTech

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 icon

Challenge

Easy

Enemies that reach the base cost lives.

  1. In EnemyData, add public int damage;.
  2. In Enemy, add public static event Action<Enemy> ReachedBase; (using System;). On the last waypoint, raise it and destroy the enemy.
  3. In GameManager, add [SerializeField] private int startLives = 20; and private int lives;, set in Start. Subscribe as above; OnReachedBase takes enemy.data.damage off 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