Waves
Lesson 4 of 18 in Coddy's Unity Game: Tower Defense course.
Enemies come in waves: a group of one kind, spaced out along the path, then a break before the next group. A wave is a few numbers, so it is a [System.Serializable] class, and the spawner keeps a List<Wave> that the Inspector shows as rows to fill in. Without [System.Serializable] Unity cannot save a Wave, the Inspector does not show the list, and it stays empty.
The timing is a coroutine: a loop that spawns, then yields new WaitForSeconds(...) to wait without stopping the rest of the game. A fireworks show works through its salvos the same way, with a pause after each:
IEnumerator Show()
{
foreach (Salvo salvo in salvos)
{
for (int i = 0; i < salvo.rockets; i++)
{
Instantiate(rocketPrefab, launcher.position, Quaternion.identity);
yield return new WaitForSeconds(salvo.gap);
}
yield return new WaitForSeconds(pause);
}
}The enemies are prefabs now. A prefab's fields can only point at assets and at objects inside the prefab, so a new enemy's waypoints array is empty. The spawner owns the path and hands it to every enemy right after Instantiate. Instantiate returns the type it is given, so with a prefab field of type Enemy it returns the new Enemy, ready to set.
Challenge
EasyThe Grunt and the Runner are prefabs now, joined by a Tank and a Boss with their own EnemyData. The Spawner object stands on WP0. Send the enemies in waves:
- In
Wave.cs, make Wave a serializable class with the public fieldsenemy(an Enemy: the prefab),count(an int) andspacing(a float, the seconds between two enemies). - In
WaveSpawner, add three serialized private fields:waves(aList<Wave>),waypoints(a Transform array) andtimeBetweenWaves(a float). - From
Start, run a coroutine that goes through the waves in order. For each one: waittimeBetweenWaves, log the wave's number from 1, asWave 1, then spawn itscountenemies at the first waypoint, give each one thewaypoints, and waitspacingafter each enemy. - After the last wave, log
All waves sent.
The Inspector fills in the game's eight waves and a break of 8 seconds. Press Play and watch the first waves come, then Check.
Try it yourself
using UnityEngine;
// Comes later: sends the enemies down the path in waves.
public class WaveSpawner : MonoBehaviour
{
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.