Creating a Countdown timer in Unity using C# script

Timers are useful in many game scenarios and that is what we are going to learn next in our learn unity series. You can use them to create delay, display time or countdown for an event. In this tutorial, we will see how to create a Countdown timer in Unity with C# script. We will also see how to set up the UI required for displaying a countdown timer and how to display the time in minutes and seconds.

If you are looking to create a simple delay then you can use Unity Coroutine or the Async await functions. If you are looking to make a stopwatch then check out our tutorial on Unity stopwatch.

Creating a countdown timer In Unity

To create a countdown timer, we will declare a float variable with some value and reduce it every frame by subtracting it with Time.deltaTime until it becomes zero.

We will also use a UI text element to display the time on the screen. So, let’s get started.

  • Create an Empty game object and name it as Timer.
  • To add the UI text. Click on the + sign in the hierarchy window and go to UI>Text-TextMeshPro.
  • Rename the text UI to Timer_display
  • Select the Timer game object and click on Add Component in the inspector window.
  • Add a new script and call it “example_timer”.
  • Open the script in your code editor.

Timer Logic

First let’s complete the logic part of the timer. We will reduce the timer value using Time.deltaTime until its zero.

using UnityEngine;

public class example_timer : MonoBehaviour
{
    float countdown=30;
    
    void Update()
    {
        if(countdown>0)
        {
            countdown-=Time.deltaTime;
        }
        
    }

}

Displaying the Timer

The above code takes care of counting down from 30 to 0. Now to display it, we need to access the text UI element.

  • We will be needing the namespace using TMPro. First let’s add that
  • Then add a public variable of type TMP_Text. Let’s call it tex.
  • We can assign the countdown to the tex variable but we need to convert countdown to string using ToString()
using UnityEngine;
using TMPro;

public class example_timer : MonoBehaviour
{
    public TMP_Text tex;
    float countdown=30;
    
    void Update()
    {
        if(countdown>0)
        {
            countdown-=Time.deltaTime;
        }
        tex.text=countdown.ToString();
        
    }

}

After Updating the code. Go back to Unity and assign the text game object to the public tex variable.

Text UI assigned to the script

Now let’s play the game and see the output.

Timer output with 5 decimal digits.

The output is displayed in seconds and with many decimal digits. So, the next step is to round off the timer to the required decimal digits.

We can use a double variable and System.Math to round off the output to two decimal places.

double b=System.Math.Round(countdown,2);
tex.text=b.ToString();

We have created a basic timer. Now let’s try to get the minutes and seconds remaining from our timer

Displaying Countdown timer in Minutes and seconds

You can get the minutes and seconds by dividing the timer variable by 60 and taking the Quotient and the Remainder. The Quotient is the number of Minutes and the Remainder is the number of seconds.

We can use the Mathf.FloorToInt to get the integer part of the Quotient and Remainder.

Here is the code to get minutes and seconds

float min=Mathf.FloorToInt(countdown/60);
float sec=Mathf.FloorToInt(countdown%60);

Let’s add two more text UI to display the minutes and seconds.

  • Go the Hierarchy and click on the +>UI>Text-TextMeshPro.
  • Name it as Minutes.
  • Add another UI text and name it as seconds.

Add two more public variable for minutes and seconds

public TMP_Text Minutes;
public TMP_Text Seconds;

Now assign the calculated values of Minutes and Seconds to the text variable.

Minutes.text="Minutes:"+min.ToString();
Seconds.text="Seconds:"+sec.ToString();

Now go back to Unity and assign the text elements to the script.

Minutes and seconds UI assigned to timer script

Now play the game and here is how the output will look like

countdown timer output with minutes and seconds

Using String Format to display time in Minutes and seconds

You can display the Minutes and Seconds in a Single text UI using a String format.

The way string formatting works is by inserting the values inside the curly braces {} which are in between the string. Inside the {} the first value is the index of the variable starting from 0 and the second is the format of the variable.

General syntax of the string format looks like this

String format explained in C#

Now let’s use the string formatting to display the center timer in “Minutes:Seconds” format.

Replace the tex.text=countdown.ToString() with the line below

tex.text=string.Format("{0,00}:{1,00}",Minutes,Seconds);

Now let’s play the game and here is how the output looks like

Timer in Minutes:Seconds format

Getting time elapsed in your Countdown timer

You can subtract the Initial value from the current value to get the time elapsed.

  • Add a UI text to display the time elapsed.
  • Let’s modify the code to take in a UI element, an initial value and an elapsed time variable.
public TMP_Text ElapsedTime;
float time_elapsed;
float initial_value;
  • Let’s assign the initial value in the Start()
void Start()
    {
        initial_value=countdown;
    }
  • In the Update(), subtract initial value from countdown to get the time elapsed.
if(countdown>0)
        {
            countdown-=Time.deltaTime;
            time_elapsed=initial_value-countdown;
        }
  • Calculate the minutes and seconds for time elapsed and use string formatting to display it. Here is how to do it
float min_e=Mathf.FloorToInt(time_elapsed/60);
float sec_e=Mathf.FloorToInt(time_elapsed%60);
ElapsedTime.text=string.Format("Elapsed Time: {0,00}:{1,00}",min_e,sec_e);
  • Now go to Unity and assign the UI element to the timer script.

Here is how the final output will look like

Final output with time elapsed

Final Unity Timer Script

Here is the script to get the final output as shown in the image above.

using UnityEngine;
using TMPro;

public class example_timer : MonoBehaviour
{
    public TMP_Text tex;
    public TMP_Text Minutes;
    public TMP_Text Seconds;
    public TMP_Text ElapsedTime;
    float countdown=300;
    float time_elapsed;
    float initial_value;

    void Start()
    {
        initial_value=countdown;
    }
    
    void Update()
    {
        if(countdown>0)
        {
            countdown-=Time.deltaTime;
            time_elapsed=initial_value-countdown;
        }
        float min=Mathf.FloorToInt(countdown/60);
        float sec=Mathf.FloorToInt(countdown%60);
        Minutes.text="Minutes:"+min.ToString();
        Seconds.text="Seconds:"+sec.ToString();
        tex.text=string.Format("{0,00}:{1,00}",min,sec);
        //Minutes and seconds calculation for elapsed time
        float min_e=Mathf.FloorToInt(time_elapsed/60);
        float sec_e=Mathf.FloorToInt(time_elapsed%60);
        ElapsedTime.text=string.Format("Elapsed Time: {0,00}:{1,00}",min_e,sec_e);
    }

}

If you have any other questions on Unity timer, feel free to leave it in the comment below. If you are looking to make a Unity timer without code then check out our article on creating a timer with visual scripting.

Next in our learning Unity journey is Animation and animators.

5 thoughts on “Creating a Countdown timer in Unity using C# script”

    • Awake gets called well before the script is executed. If you initiate the timer in awake it will not match with the time when you want the timer to start.

      Reply
    • You can add the stopwatch script to an empty object. Drag and drop the timer object to the onclick event of the button. Then select the function from the dropdown.

      Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from VionixStudio

Subscribe now to keep reading and get access to the full archive.

Continue reading