Menu
CoddyTech

A Countdown Timer

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

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

The parking meter counts down the time paid for. Write its Update() in ParkingMeter.cs (the scene links meterText):

  • timeLeft starts at 75 seconds (set in the Inspector) and goes down every frame, never below 0.
  • meterText shows the time left as minutes and seconds, rounded up to whole seconds: from 75 down to 74.01 it shows 1:15, and with 0.4 seconds left it shows 0:01.
  • Space puts in a coin: 30 more seconds, but never more than maxTime (120, which shows 2:00).
  • At 0 the text reads EXPIRED, in red (Color.red). From then on the meter stays at 0, and coins no longer go in.

Press Play, feed it a few coins, 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
    }
}
quiz iconTest yourself

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

All lessons in Building Real Games