Menu
CoddyTech

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 icon

Challenge

Easy

The 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:

  1. In Wave.cs, make Wave a serializable class with the public fields enemy (an Enemy: the prefab), count (an int) and spacing (a float, the seconds between two enemies).
  2. In WaveSpawner, add three serialized private fields: waves (a List<Wave>), waypoints (a Transform array) and timeBetweenWaves (a float).
  3. From Start, run a coroutine that goes through the waves in order. For each one: wait timeBetweenWaves, log the wave's number from 1, as Wave 1, then spawn its count enemies at the first waypoint, give each one the waypoints, and wait spacing after each enemy.
  4. 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
{
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Game: Tower Defense