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

The primary method of making a Unity timer is simple. To calculate the remaining time, create a floating-point variable and subtract the duration of the previous frame (delta time) at each frame from this amount.

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 timer will run according to how long you set the countdown time. Presumably, if you’re making a countdown timer, you might want to make sure something happens when the timer reaches 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.

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!”);

}

This method has only one problem. The “else” condition remains “true” in every frame as soon as the timer ends. This means that any action triggered when the timer reaches zero will also be triggered on every frame afterward. That means it will repeat the same step over and over.

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 we showed above is more useful because it allows you to manually control when the timer starts (by setting timerIsRunning to true).

It also means that the last action is triggered only once when the timer reaches zero.

Remember to lock the timer to zero when finished.

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

When the timer stops, the remaining time will almost always be a negative number. This is because time is subtracted in chunks that are equivalent to the duration of the last frame.

It should be set to zero when the timer runs out because while it’s not a problem now, it may cause problems later when displaying the time value.

This brings us to the next problem.

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

How to convert a time value to minutes and seconds in Unity

It seems like a simple task, but it cannot be easy to display a time value in minutes and seconds in Unity.

This is because there were many ways to do it.

This method is beneficial because it allows us to avoid many of the common problems you may encounter while displaying the time accurately in just a few steps.

Both minutes and seconds must be calculated separately from the raw time value to display time accurately.

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 computational function that converts the remainder after dividing one number by another.

In this example, modulo converts the number of seconds from the total time value that does not make up a full minute.

It is one of the excellent methods to get just seconds of a time display.

The value of the results will be variable. You should use Mathf.FloorToInt to round to the largest integer value.

Stay informed in 5 minutes

We send the latest and exclusive reports for the mobile game industry to your email inbox.

    We won't send you spam. Unsubscribe at any time.

    Related Posts
    career advice
    Read More

    Career in Games #1: How to apply for a job

    At our Mobidictum Career in Games event, we discussed many issues related to the industry. Elif Karaata from MagicLab shared her tips that will make a difference during job application for those who want to enter the industry at our event.