Countdown Timer Tutorial for Unity

A countdown timer is a virtual clock that counts from a set time until 0.

To make a Countdown timer in Unity, you'll need to create a script that will store the amount of time that will be counted down and will display it in 00:00 format.

Unity countdown timer top-left corner.

The timer will feature these formats:

  • Days:Hours:Minutes:Seconds:Milliseconds
  • Hours:Minutes:Seconds:Milliseconds
  • Minutes:Seconds:Milliseconds
  • Seconds:Milliseconds
  • Plus all the above but without Milliseconds

Steps

To make a countdown timer in Unity, follow the steps below:

  • Create a new script, call it 'SC_CountdownTimer', remove everything from it then paste the code below:
  • The countdown timer C# script will subtract from the total value until reaching 0 and will apply the formatted time to a Text element.

SC_CountdownTimer.cs

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

public class SC_CountdownTimer : MonoBehaviour
{
    public enum CountdownFormatting { DaysHoursMinutesSeconds, HoursMinutesSeconds, MinutesSeconds, Seconds };
    public CountdownFormatting countdownFormatting = CountdownFormatting.MinutesSeconds; //Controls the way the timer string will be formatted
    public bool showMilliseconds = true; //Whether to show milliseconds in countdown formatting
    public double countdownTime = 600; //Countdown time in seconds

    Text countdownText;
    double countdownInternal;
    bool countdownOver = false;

    // Start is called before the first frame update
    void Start()
    {
        countdownText = GetComponent<Text>();
        countdownInternal = countdownTime; //Initialize countdown
    }

    void FixedUpdate()
    {
        if (countdownInternal > 0)
        {
            countdownInternal -= Time.deltaTime;

            //Clamp the timer value so it never goes below 0
            if (countdownInternal < 0)
            {
                countdownInternal = 0;
            }

            countdownText.text = FormatTime(countdownInternal, countdownFormatting, showMilliseconds);
        }
        else
        {
            if (!countdownOver)
            {
                countdownOver = true;

                Debug.Log("Countdown has finished running...");

                //Your code here...
            }
        }
    }

    string FormatTime(double time, CountdownFormatting formatting, bool includeMilliseconds)
    {
        string timeText = "";

        int intTime = (int)time;
        int days = intTime / 86400;
        int hoursTotal = intTime / 3600;
        int hoursFormatted = hoursTotal % 24;
        int minutesTotal = intTime / 60;
        int minutesFormatted = minutesTotal % 60;
        int secondsTotal = intTime;
        int secondsFormatted = intTime % 60;
        int milliseconds = (int)(time * 100);
        milliseconds = milliseconds % 100;

        if (includeMilliseconds)
        {
            if (formatting == CountdownFormatting.DaysHoursMinutesSeconds)
            {
                timeText = string.Format("{0:00}:{1:00}:{2:00}:{3:00}:{4:00}", days, hoursFormatted, minutesFormatted, secondsFormatted, milliseconds);
            }
            else if (formatting == CountdownFormatting.HoursMinutesSeconds)
            {
                timeText = string.Format("{0:00}:{1:00}:{2:00}:{3:00}", hoursTotal, minutesFormatted, secondsFormatted, milliseconds);
            }
            else if (formatting == CountdownFormatting.MinutesSeconds)
            {
                timeText = string.Format("{0:00}:{1:00}:{2:00}", minutesTotal, secondsFormatted, milliseconds);
            }
            else if (formatting == CountdownFormatting.Seconds)
            {
                timeText = string.Format("{0:00}:{1:00}", secondsTotal, milliseconds);
            }
        }
        else
        {
            if (formatting == CountdownFormatting.DaysHoursMinutesSeconds)
            {
                timeText = string.Format("{0:00}:{1:00}:{2:00}:{3:00}", days, hoursFormatted, minutesFormatted, secondsFormatted);
            }
            else if (formatting == CountdownFormatting.HoursMinutesSeconds)
            {
                timeText = string.Format("{0:00}:{1:00}:{2:00}", hoursTotal, minutesFormatted, secondsFormatted);
            }
            else if (formatting == CountdownFormatting.MinutesSeconds)
            {
                timeText = string.Format("{0:00}:{1:00}", minutesTotal, secondsFormatted);
            }
            else if (formatting == CountdownFormatting.Seconds)
            {
                timeText = string.Format("{0:00}", secondsTotal);
            }
        }

        return timeText;
    }
}
  • Create a new UI text, by right-clicking on the Hierarchy view -> UI -> Text and name it 'Countdown'

Unity create new UI text

  • Change 'Countdown' Rect Transform alignment to the top left, pivot to (0, 1), Pos X and Pos Y to 5, Width to 300, and Height to 60

  • Change the 'Countdown' Text Font Style to Bold, Font Size to 34, Alignment to Left Center, and Color to white

Unity Text Component Inspector Arial Bold Font Size 34

  • Attach the SC_CountdownTimer script to the 'Countdown' object that has a Text component.

You'll notice the script has a few variables:

  • Countdown Formatting controls what time units will be included in the string formatting.
  • Show Milliseconds controls if the millisecond count should be shown.
  • Countdown Time is the duration of the countdown in seconds, for example, the value 600 corresponds to 10 minutes.

After pressing Play you should notice the text populated with a countdown timer:

At 0 seconds the script will print a line in the console, signalizing that the countdown has finished, use that part of the script to add your own functionality.

Links
Unity 6