Waves of Enemies
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 44 of 50.
Challenge
MediumThe enemies now come in waves, and the waves are data. Keep everything from the earlier lessons. The arena has no enemies of its own any more: the Grunt and Dasher prefabs carry your scripts, four spawn points stand in the corners, and the Spawner object in the middle has the WaveSpawner script.
- In
WaveSet.cs, add a[System.Serializable]classWavewithpublic Enemy enemy(the prefab),public int countandpublic float spacing.WaveSetis a ScriptableObject with[CreateAssetMenu], apublic List<Wave> wavesand apublic float restBetweenWaves. The scene'sArenaasset holds three waves (3 grunts 0.5 s apart, 2 dashers 1 s apart, 5 grunts 0.4 s apart) and a rest of 2 seconds. Enemygetspublic static event Action<Enemy> Died, raised with the enemy right before it is destroyed.WaveSpawnerhaswaveSetandspawnPointsfrom the Inspector, andpublic int Wave { get; private set; }, the number of the wave in play. FromStart, a coroutine runs the asset's waves in order. For each: add 1 toWaveand log it, asWave 1; spawn the wave'scountenemiesspacingseconds apart, enemyi(from 0) atspawnPoints[i % spawnPoints.Length]; wait until no enemy is left alive; then restrestBetweenWavesseconds. After the last wave the set starts again from its first, andWavekeeps counting: 4, 5 and so on.- Count the enemies alive with the
Diedevent: subscribe inOnEnableand unsubscribe inOnDisable. The spawner only reads the asset: in the Editor, a change made to an asset while the game runs stays in the asset after Play.
Press Play and survive a few waves, then Check.
Try it yourself
using UnityEngine;
public class WaveSpawner : MonoBehaviour
{
// A later lesson fills this in: sends the waves into the arena.
}
All lessons in Game Architecture in Unity
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular Turret10Project: Arena Survivor
The HeroEnemy Types