Menu
CoddyTech

A Countdown Timer

Part of the Building Real Games section of Coddy's Unity journey. Lesson 4 of 60.

A countdown keeps the time left in a float and takes Time.deltaTime off it every frame. The last frame rarely lands on exactly 0, so Mathf.Max stops it there, and the end must happen once. This fuse gives the player 5 seconds to defuse a bomb:

public TMP_Text fuseText;
public float fuse = 5f;
private bool exploded;

void Update()
{
    if (exploded)
    {
        return;
    }

    fuse = Mathf.Max(fuse - Time.deltaTime, 0f);
    fuseText.text = "Fuse: " + Mathf.CeilToInt(fuse);

    if (fuse == 0f)
    {
        exploded = true;
        fuseText.text = "BOOM";
        fuseText.color = Color.red;
    }
}

Mathf.CeilToInt rounds up, which is what a countdown shows: 5 for the whole first second (4.99 rounds up to 5), 1 during the last one, and 0 only when the time is up. (int)fuse would cut 4.99 down to 4 and show 0 for the whole last second while the bomb is still ticking; Mathf.RoundToInt would show 0 for the last half second. A longer countdown shown in minutes and seconds follows the same rule: round the time up to whole seconds first, then format those.

The early return keeps BOOM on screen: without it, the next frame would write Fuse: 0 over it. A text has a color too, and fuseText.color = Color.red turns it red.

challenge icon

Challenge

Easy

Make the parking meter count down the time paid for.

  1. In Update(), take Time.deltaTime off timeLeft, never below 0, and show Mathf.CeilToInt(timeLeft) as minutes and seconds: 1:15.
  2. Space adds 30 seconds, up to maxTime (2:00).
  3. At 0, show EXPIRED in Color.red. Start Update() with if (timeLeft == 0f) return; so it stays that way.

Press Play and feed it coins: it stops at 2:00. Then Check.

Try it yourself

using UnityEngine;
using TMPro;

public class ParkingMeter : MonoBehaviour
{
    public TMP_Text meterText;
    public float timeLeft = 60f;
    public float maxTime = 120f;

    void Update()
    {
        // Count timeLeft down and show it as minutes and seconds; Space adds 30 seconds
    }
}

All lessons in Building Real Games

Practice on your own: Unity playground