How to create a timer in Unity?

How to make unity countdown timer in simplest way?
Unity Timer
The primary methods of making a Unity countdown timer

Creating a countdown timer in Unity is a simple yet essential task for many games or applications. Here’s how you can create one, manage its functionality, and display the remaining time in a readable format, such as minutes and seconds.

Basic Timer Setup

To set up a basic timer, you will need a floating-point variable to hold the remaining time, and in Unity’s Update method, you will subtract the time that has passed since the last frame (Time.deltaTime). This creates a countdown effect.

E.G:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class Timer : MonoBehaviour

{

    public float timeRemaining = 10;

    void Update()

    {

        if (timeRemaining > 0)

        {

            timeRemaining -= Time.deltaTime;

        }

    }

}

This is the basic method of creating a timer in Unity. The countdown will proceed based on the duration you specify. In most cases, implementing a countdown timer will likely require triggering a specific action once the timer hits zero.

How to trigger a countdown action

In the previous example, we knew if the timer was running by specifying a certain amount of time. However, simply knowing the timer is running isn’t enough if you want to execute an action when the countdown ends.

To ensure that an action is triggered when the timer reaches zero, you can use a conditional statement to check if the remaining time has elapsed and then perform the desired operation.

What if you want to trigger an action when the timer runs out?

For example, ending the game or adjusting the time display, etc. Countdown doesn’t make much sense if nothing happens at the end. The easiest way to do this is with the “else” condition.

E.G.:

if (timeRemaining > 0)

{

    timeRemaining -= Time.deltaTime;

}

else

{

    Debug.Log(“Time has run out!”);

}

The only issue with this method is the “else” condition. Once the timer ends, the “else” condition remains “true” for every frame, which means that the action triggered when the timer reaches zero will be executed repeatedly on every frame afterward.

As a result, the action continuously repeats, leading to unwanted repetition of the same step. Therefore, you need to implement an additional control mechanism to ensure that the timer’s end is handled only once.

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class Timer : MonoBehaviour

{

    public float timeRemaining = 10;

    public bool timerIsRunning = false;

    private void Start()

    {

        // Starts the timer automatically

        timerIsRunning = true;

    }

    void Update()

    {

        if (timerIsRunning)

        {

            if (timeRemaining > 0)

            {

                timeRemaining -= Time.deltaTime;

            }

            else

            {

                Debug.Log(“Time has run out!”);

                timeRemaining = 0;

                timerIsRunning = false;

            }

        }

    }

}

The example provided is more useful because it allows you to manually control when the timer starts (by setting timerIsRunning to true). Additionally, this method ensures that the action is triggered only once when the timer reaches zero.

Remember to reset the remaining time to zero once the timer is finished.

You might also notice that we manually set timeRemaining to zero when the timer expires.

When the timer stops, the remaining time is often a negative number because time is subtracted in chunks equivalent to the duration of the last frame. Therefore, resetting the time to zero is important to avoid potential issues when displaying the time value later.

This brings us to the next issue. To convert a float value to minutes and seconds, you must first break down the time value into minutes and seconds.

How do you convert a time value to minutes and seconds in Unity?

While this may seem like a simple task, displaying a time value in minutes and seconds accurately in Unity can be somewhat complex. Using this method helps to avoid common problems associated with displaying time accurately and allows you to resolve the issue in just a few steps.

Minutes and seconds need to be calculated separately from the raw time value to display the time correctly.

To calculate the minutes, divide the remaining time by 60, for example:

float minutes = Mathf.FloorToInt(timeRemaining / 60);

Use the modulo operation (%) like this to calculate the second.

float seconds = Mathf.FloorToInt(timeRemaining % 60);

What is the Modulo operation?

The modulo operation is a mathematical function that calculates the remainder after dividing one number by another. In this example, the modulo operation is used to determine the seconds that remain after accounting for whole minutes in the total time value.

In other words, it helps isolate the seconds that do not complete a full minute when breaking down the total time into minutes and seconds. This method is highly effective for extracting only the seconds portion from a time value.

The result of the modulo operation can vary. Therefore, it is recommended to use Mathf.FloorToInt to round the result to the nearest whole number.