Unity timer tutorial: Creating Countdown timer with C# script

Looking to create a Countdown timer with seconds and minutes functionality? Then this is the tutorial for you. We will also see how to set up the UI required for displaying a countdown timer in Unity 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.

The codes have been tested in Unity editor and the output is displayed for your reference.

Unity Timer terminologies you should know

  1. DeltaTime– Intervals between frames.
  2. FixedDeltaTime– Interval between physics frames.
  3. Time.time– this is the time passed from the start of the game.
  4. Fixedtime– time passed from the start of the game to the recent fixed update.
  5. Timescale– the speed at which time passes in your game.
timer display on unity game view

Creating a countdown timer In Unity

Unity Countdown timer C# Script

using UnityEngine;
using UnityEngine.UI;

public class Timerexample : MonoBehaviour
{

float cntdnw = 30.0f;
public Text disvar;

void Update() 
{     
  if(cntdnw>0)     
  {         
    cntdnw -= Time.deltaTime;     
  }     
  double b = System.Math.Round (cntdnw, 2);     
  disvar.text = b.ToString ();     
  if(cntdnw < 0)     
  {         
    Debug.Log ("Completed");     
  } 
}
}

Let’s see what the above code does. “using UnityEngine.UI” is needed to call the text variable. Without that, you won’t be able to access the UI elements

Free Unity asset banner

  1. We declared a variable cntdnw and set its value to 30. It should be set as a float because Time.deltaTime will return a float variable.
  2. Text variable disvar will be used to display the timer in your game.
  3. Inside the Update() function we are checking if the timer is greater than zero. If we don’t do this the timer will go into negative too.
  4. We are subtracting the time passed between every frame using the Time.deltaTIme function.
  5. Round-off the float to the number of decimals as required. We are doing it with the variable b.
  6. Then we convert the float variable to string before assigning it to the display variable.
  7. We are checking if the timer has reached zero and then we can execute the required code as per game needs.

Display the Timer Text using the Unity timer code

  • Create an Empty gameobject and name it as timer.
  • Select your timer gameobject and go to the inspector window.
  • Click of Add Component and add a new Script called Timerexample.
timer example script attached to the timer gameobject
  • Copy and paste the code above to your script.
  • Add a new Text UI to your scene by going to Create>UI>Text and name it as Timer Display.
  • Adjust the font size to your requirement.
  • Drag and drop the Timer Display gameobject to the text variable (Disvar) in the timer gameobject.
  • Play the game and you should see the timer working.

Tip: Always initialize your private variables in the Start function and not the awake function. You can read the difference between them in our Unity Awake vs Start post.

Completed message displayed after Unity timer value less than 0

Using a Text mesh pro text UI for Timer display

The new version of Unity has moved the text UI in the legacy menu and will slowly remove the support for it.

adding TMP text UI in Unity

If you add a Text mesh pro UI text to your scene you need to make the following changes to the script.

  1. Change “using UnityEngine.UI” to “using TMPro”
  2. The data type of the text element will be TMP_Text.

Rest of the procedure and code will remain same. Here is how the final script will look like if you are using text mesh pro.

using UnityEngine;
using TMPro;

public class Timerexample : MonoBehaviour
{

float cntdnw = 30.0f;
public TMP_Text disvar;

void Update() 
{     
  if(cntdnw>0)     
  {         
    cntdnw -= Time.deltaTime;     
  }     
  double b = System.Math.Round (cntdnw, 2);     
  disvar.text = b.ToString ();     
  if(cntdnw < 0)     
  {         
    Debug.Log ("Completed");     
  } 
}
}

Displaying time in Minutes and seconds

In our above examples the timers are displayed in decimal format but the actual time should be displayed in Minutes:Seconds

Unity timer in Minutes:Seconds format

We need to add two more Text UI to our scene. One will be for minutes and the other will be for seconds.

You can name them minutes and seconds.

Now let’s go back to the script and add two more public text variables.

public Text Minutes;
public Text Seconds;

In case of Text mesh pro the data type will be TMP_Text.

Mathf has a function called FloortoInt which we can use to get the minutes and seconds.

Then we can assign those values to the text variables.

Unity timer C# script with Seconds and minutes display

using UnityEngine;
using UnityEngine.UI;

public class Timerexample : MonoBehaviour
{

float cntdnw = 30.0f;
public Text disvar;
public Text Minutes;
public Text Seconds;

void Update() 
{     
  if(cntdnw>0)     
  {         
    cntdnw -= Time.deltaTime;     
  }     
  double b = System.Math.Round (cntdnw, 2);     
  disvar.text = b.ToString ();  
  float minutes= Mathf.FloorToInt(cntdnw /60);  
  Minutes.text=minutes.ToString();
  float seconds=Mathf.FloorToInt(cntdnw%60);
  Seconds.text=seconds.ToString();
  if(cntdnw < 0)     
  {         
    Debug.Log ("Completed");     
  } 
}
}

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. Here is a code sample

string.Format("{0,00}:{1,00}",minutes,seconds);

The way string formatting works is by inserting the values inside the curly braces {} which are inbetween 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#

Getting time elapsed in your Countdown timer

You can either count up from zero to get the time elapsed or you can subtract the current value of the countdown variable with the starting value to get the time elapsed.

Count up code

float contup=0;
void Update()
{
 
    contup += Time.deltaTime;     
     
}

Subtracting from the initial value

float cntdnw = 30.0f;
float initial_value=0;
float time_elapsed=0;

void Start()
{
   initial_value=cntdnw;
}

void Update() 
{     
  if(cntdnw>0)     
  {         
    cntdnw -= Time.deltaTime;     
  } 
time_elapsed=initial_value-cntdnw;   
} 

If you have any other questions on Unity timer, feel free to leave it in the comment below. If you like the article share it with your friends.

Top online courses in Development

5 thoughts on “Unity timer tutorial: Creating Countdown timer with 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.