Menu
CoddyTech

Every Wave

Lesson 6 of 25 in Coddy's Unity Game: Tower Defense course.

One wave is not a game. The coroutine goes through every wave in order, with a break before each so the player can get ready, and tells the Console which wave starts. The break is one more WaitForSeconds, at the top of the loop:

for (int i = 0; i < waves.Count; i++)
{
    yield return new WaitForSeconds(timeBetweenWaves);
    // log the wave, then spawn waves[i] as before
}

The waves count from 0 in the list and from 1 for the player, so the Console shows "Wave " + (i + 1).

challenge icon

Challenge

Medium

Send every wave, with a break before each.

  1. In WaveSpawner, add [SerializeField] private float timeBetweenWaves = 8f;.
  2. Loop over waves: wait timeBetweenWaves, log "Wave " + (i + 1), then spawn waves[i] as before.
  3. After the loop, log All waves sent.

Press Play: after 8 seconds the Console says Wave 1 and the Grunts come. Then Check.

Try it yourself

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WaveSpawner : MonoBehaviour
{
    [SerializeField] private List<Wave> waves = new List<Wave>();
    [SerializeField] private Transform[] waypoints;

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

    IEnumerator RunWaves()
    {
        Wave wave = waves[0];
        for (int n = 0; n < wave.count; n++)
        {
            Enemy enemy = Instantiate(wave.enemy, waypoints[0].position, Quaternion.identity);
            enemy.waypoints = waypoints;
            yield return new WaitForSeconds(wave.spacing);
        }
    }
}

All lessons in Unity Game: Tower Defense

Practice on your own: Unity playground