Menu
CoddyTech

Countdown

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

Between waves the player builds, and a countdown shows how long is left. A player who is ready can call the next wave early with a button. The break is a loop in a coroutine that yields null, so it runs once per frame: it counts the time down, shows it, and ends when the time is up or when the button asked for the wave. The button only sets a bool, and the loop reads it:

while (left > 0f && !skipRequested)
{
    // show the seconds left, count down, wait a frame
}
skipRequested = false;

The bool goes back to false after it is used, or every break after the first would end at once. Mathf.CeilToInt rounds up, so 2.3 seconds left reads 3. yield return StartCoroutine(Countdown()); runs the countdown and waits for it to finish.

challenge icon

Challenge

Hard

Count down to each wave; a button calls it early.

  1. In WaveSpawner, add serialized countdownText (TMP_Text) and nextWaveButton (GameObject), private bool callNow; and public void CallNextWave() { callNow = true; }.
  2. Replace the break with yield return StartCoroutine(Countdown());: show the button and, while time is left and not callNow, show Next wave in 8, rounded up, each frame.
  3. Then set callNow back to false, clear the text and hide the button.

Press Play: Next Wave skips the wait. 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;
    [SerializeField] private float timeBetweenWaves = 8f;

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

    IEnumerator RunWaves()
    {
        for (int i = 0; i < waves.Count; i++)
        {
            yield return new WaitForSeconds(timeBetweenWaves);
            Debug.Log("Wave " + (i + 1));
            Wave wave = waves[i];
            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);
            }
        }
        Debug.Log("All waves sent");
    }
}

All lessons in Unity Game: Tower Defense

Practice on your own: Unity playground