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
MediumMake each wave wait until the arena is clear.
- In
Enemy, addpublic static event Action<Enemy> Died;and callDied?.Invoke(this);just beforeDestroy(gameObject);. - In
WaveSpawner, countalive: add 1 per spawn, take 1 off in a method thatOnEnableadds toEnemy.DiedandOnDisableremoves. - 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
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular TurretRecap: Twin Cannon4Serialized Data
Serializable ClassesLists in the InspectorEnums in the InspectorRecap: Loot TableRecap: Roll the Loot7State Machines
States as ClassesThe Alert StateA State MachineTransitionsEnemy BrainsThe Knight AttacksRecap: Door States10Project: Arena Survivor
The HeroEnemy Types2Interfaces in Unity
IDamageableInterfaces and TryGetComponentGetComponentsRecap: Interact KeyRecap: Nearest in ReachPractice on your own: Unity playground