Timers are useful in many game scenarios. 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.
Unity Timer terminologies you should know
- DeltaTime- Intervals between frames.
- FixedDeltaTime- Interval between physics frames.
- Time.time- this is the time passed from the start of the game.
- Fixedtime- time passed from the start of the game to the recent fixed update.
- Timescale- the speed at which time passes in your game.
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. The namespace “using UnityEngine.UI” is needed to use the UI text variable. Without that, you won’t be able to access the UI elements.
- 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.
- Text variable “disvar” will be used to display the timer in your game.
- 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.
- We are subtracting the time passed between every frame using the Time.deltaTIme function.
- Then we are Rounding-off the float to the number of decimals as required. We are doing it with the variable b.
- Then we convert the float variable to string before assigning it to the display variable.
- 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.
- 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.
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.
If you add a Text mesh pro UI text to your scene you need to make the following changes to the script.
- Change “using UnityEngine.UI” to “using TMPro”
- 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.
Unity Timer script with TMPro
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 Countdown timer 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
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
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.
Unity script for Time elapsed
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 are looking to make a Unity timer without code then check out our article on creating a timer with visual scripting.
Well explained
Why should we not initiate the timer variable in awake function?
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.
How do I add these functions to the buttons I have created in the stopwatch example?
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.