Menu
CoddyTech

Clear the Arena

Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 55 of 64.

An event marked static belongs to the class, not to one object. There is one Enemy.Died for every enemy there will ever be, so the spawner can subscribe with Enemy.Died += OnEnemyDied; before any enemy exists, and each enemy raises it with itself as the argument. The same idea in plain C#:

public class Coin
{
    public static event Action<Coin> Picked;

    public void Pick()
    {
        Picked?.Invoke(this);
    }
}

public class Purse
{
    private int coins;

    public Purse()
    {
        Coin.Picked += OnPicked;   // no Coin needed yet
    }

    void OnPicked(Coin coin)
    {
        coins++;
    }
}

An instance event is reached through an object, as hero.Died; a static one through the class name, as Coin.Picked. A static event outlives every object, so unsubscribe in OnDisable, or a destroyed spawner stays on its list.

challenge icon

Challenge

Medium

Make each wave wait until the arena is clear.

  1. In Enemy, add public static event Action<Enemy> Died; and call Died?.Invoke(this); just before Destroy(gameObject);.
  2. In WaveSpawner, count alive: add 1 per spawn, take 1 off in a method that OnEnable adds to Enemy.Died and OnDisable removes.
  3. After a wave spawns, wait while alive > 0.

Press Play and defeat wave 1: wave 2 comes 2 seconds later. Then Check.

Try it yourself

using System.Collections;
using UnityEngine;

public class WaveSpawner : MonoBehaviour
{
    [SerializeField] private WaveSet waveSet;
    [SerializeField] private Transform[] spawnPoints;

    public int Wave { get; private set; }

    void Start()
    {
        StartCoroutine(RunWaves());
    }

    IEnumerator RunWaves()
    {
        while (true)
        {
            foreach (Wave wave in waveSet.waves)
            {
                Wave++;
                Debug.Log("Wave " + Wave);
                for (int i = 0; i < wave.count; i++)
                {
                    Transform point = spawnPoints[i % spawnPoints.Length];
                    Instantiate(wave.enemy, point.position, Quaternion.identity);
                    yield return new WaitForSeconds(wave.spacing);
                }
                yield return new WaitForSeconds(waveSet.restBetweenWaves);
            }
        }
    }
}

All lessons in Game Architecture in Unity

Practice on your own: Unity playground