Making a simple timer in Unity

Timers are used in a lot of places in game development. Timers are used differently in different games. Some games use it as a countdown timer, some use it to increase the game difficulty and some use it to spawn enemies or power-up in the game. Unity timer function makes all this very easy to accomplish. With a simple addition and subtraction, you can change the timer from a countdown to a counter. You can also display the timer in minutes and seconds or as a rounded figure.

In Unity, the timer can be done with a simple line of code. In this post, we will see how you can make timers for different scenarios. I will also include codes that you can copy and directly use in your game. The codes have been tested in Unity editor and the output is displayed for your reference. My suggestion would be to try and write the first-timer code yourself to get a detailed understanding of the Unity timer function.

Remember the following before working with timers in Unity

  • Time works based on framerate and physics in Unity.
  • Any time parameter based on physics will have the term “fixed” in front of it.
  • Time.deltaTime returns a float.

Unity Timer- most useful inbuilt functions

  1. DeltaTime- Intervals between frames.
  2. FixedDeltaTime- Interval between physics frames.
  3. 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.

You can read about more Time functions here

Creating a countdown timer In Unity

Unity Countdown timer Script

using System.Collections; 
using System.Collections.Generic; 
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 see what the above code does. “using UnityEngine.UI” is needed to call the text variable. Without that, it will throw an error.

  1. I 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 are converting 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.

Using the code in Unity to create a countdown timer

  1. Create an Empty gameobject and add the timer script to it. Rename it as timer.
  2. Create an UI text gameobject and name it as Timer UI.
  3. Drag and drop the Timer UI gameobject to the text variable in the timer gameobject.
  4. Play the game and you should see the timer working.

The video below shows how to use the code above to create a countdown timer.

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

Unity timer
Output 1
timer code output
Output 2

Making a stopwatch in Unity

A stopwatch is not that different from a regular timer. The only thing is you need a start, stop, and a reset option for this stopwatch. You can do that simply with the help of Boolean variables. Lets see the code for a stopwatch.

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine;
using UnityEngine.UI;

public class Timerexample : MonoBehaviour
{

float val;
bool srt,stp,rst;
public Text disvar;

void Start()
{
val=0;
srt=false;
stp=false;
rst=false;
}

void Update() 

{ 

if(srt)     

{         
val += Time.deltaTime;    
} 

double b = System.Math.Round (val, 2);     

disvar.text = b.ToString ();    
}
public void stopbutton()
{
srt=false;
}
public void resetbutton()
{
srt=false;
val=0;
}
public void startbutton()
{
start=true;
}
}

You need to create three buttons for the Start, Stop and Reset functions. You can link them to the respective function in the code. Also, a text UI for the timer is required. Once you have done this setup just add the above code and your stopwatch is ready.

Making a timer with coroutine

You can implement a timer with Unity Coroutine with much ease. Coroutines are useful to execute a function over a number of frames. The main difference between using a coroutine and normal time.deltatime is displaying time. If you want to display a timer that changes every frame then it’s better not to use a coroutine. But if you want to execute a function after a time period then coroutine is the easiest way.

One other important thing to note is coroutine can be used only with monobehaviour. If you are looking to make a Unity timer without monobehaviour then use the first method.

Let us see the sample code

public float delay = 5f;
private int ammo=0;
void Start()
{
    StartCoroutine("Delaythis");
}
IEnumerator Delaythis()
{
    
        yield return new WaitForSeconds(delay)
        ammo=50;


}

If you are using the yield statement then the return type should be IEnumerator. In the above code the value of the ammo variable is set to 50 after 5 seconds.

FAQs on Unity timers

  1. How to make a simple countdown timer?

    Define a variable from which you want to start the countdown. Define it as a float as deltaTime returns a float. The next thing is to subtract deltaTime from your variable. That's it, the code is added below for your reference.

  2. How to display timer in UI?

    First, you need to create a UI element of type Text. Then assign the timer variable to the text variable using the ToString() function. You can see the code for example. You need to add “using UnityEngine.UI” for the Text variable.

  3. How to calculate Time elapsed in Unity?

    If you are looking for the time that has passed since the start of the game then, you can use the Time.time function to get it. If you are looking for the time since the level has loaded then you can use Time.timeSinceLevelLoad function.

  4. How to create slow motion effect in Unity?

    You can use the timescale function to control the speed at which time passes in your game. By default this value is set at 1, by changing this to a value between 0 and 1, you can create a slow-motion effect. Some use this value to pause a game but you need to be careful as it only affects things inside Update or FixedUpdate functions.

  5. How to get time in Minutes or seconds in Unity?

    minutes = Mathf.FloorToInt(timevar /60);
    seconds = Mathf.FloorToInt(timevar%60);

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

5 thoughts on “Making a simple timer in Unity”

    • 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.