Making a simple timer in Unity(Unity timer simplified)

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 powerup 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

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

Sample Unity 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 need 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 decimal 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.

Tip: Always initialize your 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 start, stop and reset function. 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.

3 thoughts on “Making a simple timer in Unity(Unity timer simplified)”

    • 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

Leave a Reply

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