unity 3d student

Beginner B06 – Simple Timer


How to make a simple scripted timer in Unity using Time.deltaTime and a float variable.

Code Used

//A simple countdown timer
  1. var myTimer : float = 5.0;
  2.  
  3. function Update () {
  4.  if(myTimer > 0){
  5.   myTimer -= Time.deltaTime;
  6.  }
  7.  if(myTimer <= 0){
  8.   Debug.Log("GAME OVER");
  9.  }
  10. }

Further Reading

Share via Social Media

  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • Add to favorites

31 Comments

    Hello
    sorry, what does it means:
    ” myTimer > 0 ” ?

    You didn’t use this in the video :-P. Thanks

    • Pretty sure I did! see 2:08..

    Hey. Im quite new to unity and I have no experience at all with Javascript, however I’m quite familiar with C#.

    I tried to convert your script to C# but I had some problems.

    First of all, here is the code.

    using UnityEngine;
    using System.Collections;

    public class timer : MonoBehaviour {

    float mytimer = 5.0f;
    void Update () {

    mytimer -= Time.deltaTime;
    if(mytimer <= 0 ){
    Debug.Log("Game Over");
    Destroy(gameObject);
    }
    }
    }

    It's working like this. But if I take out "Destroy(gameObject);"
    Then it keeps saying "Game Over" until I press stop. Why is this?
    Is there any way to only check the if statement once?

    Sorry if this was hard to understand, english is not my native language.
    Thanks in advance.

    • Hi there, first off your English is fine, what you need to understand is that an IF statement simply checks for a condition, so ‘is X less than or equal to Y’ – and returns true if it is – the point is in the example you give, the timer continues to count down below 0, so the Game Over log will continue to print each frame, until mytimer is no longer less than 0. So it is not a case of firing the IF once, it is more that you want to change what the subtraction from the counter is doing – so you might say for example

      if(mytimer > 0){
      mytimer -=Time.deltaTime;
      }else if(mytimer<=0){
      Debug.Log("Game Over");
      }

      that way you stop the constant subtraction from the value of mytimer, but the IF will still continue to print Game Over of course, as it is still less than or equal to 0. This would be where you might put in a boolean flag, simply to set a true / false value to stop the whole IF statement from running if a variable becomes true.

    Is there a little error in your logic? If deltaTime is the time since the game started then you’re not going to get a full 5 seconds by repeatedly subtracting that. You should probably just say

    if (Time.deltaTime > mytimer)
    {
    Debug.Log(“Game Over”)
    }

    • Hi Pete, no you’re thinking of Time.time which is the time since game start. Thanks for taking time to comment :)

    I’m assuming that deltatime can’t be used if you want it to count up? but a loop would right? AND, what would be the easiest way to get the time to display?

    • Hey Devlus below is a simple stopwatch timer that uses deltaTime to count up. I even added a variable that allows you to decide when it is running.

      var running : boolean = false;
      var timeElapsed : float = 0;

      function Update() {
      if (running) timeElapsed += Time.deltaTime;
      Debug.Log(timeElapsed);
      }

    If I wanted to ‘add’ time, would it be possible because every time I add “+” I always get an error.

    • presuming the error is related to expressions, then you need to use ‘+=’ not just ‘+’

    Just for fun here is the C# equivalent code(no performance alterations made).

    using UnityEngine;
    using System.Collections;

    public class TimerCSharp : MonoBehaviour {

    public float myTime = 5.0f;

    // Update is called once per frame
    void Update () {
    if(myTime>0) {
    myTime -= Time.deltaTime;
    }
    if(myTime<=0) {
    Debug.Log("GAME OVER");
    }

    }
    }

  • var myTimer : int = 5;

    function Update () {
    if(myTimer > 0)
    {
    myTimer -= Time.deltaTime;
    }

    if(myTimer <=0)
    {

    Application.LoadLevel(12);
    }
    guiText.text = "Time:" + myTimer;

    }
    HOw do I slow down my timer?

    • slow it down in what sense? you could divide the number you’re subtracting from myTimer (ie. Time.deltaTime)

    Hi everyone, loving the tutorials but ofc, I have a question.

    So far I have:

    =============================================================================
    var aTimer : float = 5.0;
    var aTest : boolean = true;

    function Update () {
    if (aTimer > 0)
    {
    aTimer -= Time.deltaTime;
    }
    if (aTest & (aTimer <= 0))
    {
    aTest = false;
    Debug.Log(gameObject.name + ” = PING!”);
    }
    }
    =============================================================================

    But I also have 2 objects (having followed the tutorials thus far), one called ‘Cube’ and one called ‘Ghost Cube’.

    ‘Cube’ is in the scene from the start, then drops, and bounces around a bit.
    ‘Ghost Cube’ enters the scene (at least visually [as it's an empty object with a prefab applied to the instantiate script]) when the Space Bar is pushed.

    What I would ideally like to happen, is the ‘deltaTime’ to start counting from when the ‘Ghost Cube’ is instantiated. But I can’t for the life of me work out how.

    If this is taught in a later tutorial that I haven’t reached, please forgive the spam. If it isn’t, perhaps this could be included in a later tutorial?

    Thanks a lot mate, and keep up the excellent work!

    PS: Do you have any completed Unity projects out there on the web that we can have a fiddle with?

    • Kerry, when you insantiate, also address the object this script is on by finding the object and using getcomponent() to address the script an set your Boolean to true- the you can say if timer is more than 0 and Boolean is true then start subtracting time, see the getcomponent tute, good luck!

    Hi, I got the timer to run but i was wondering if there was any additional code i can add to make the game stop when the timer reaches 0?

    • depends what you mean by stop the game. there will be other factors and scripts running presumably. you may want to establish a boolean in some kind of manager script that handles this stuff and when the timer runs out, set this variable to true, something like gameover = true; and then have other scripts rely on that being false in order to run.

    First off I love your site and have learned alot using it, thanks for the great resources you provide here.

    Now I was wondering… How would I take this timer and set it to start upon a specific action/trigger rather then upon game start? Say for example I wanted to shoot the cube at the wall and destroy the wall. But I wanted a 5 second timer started upon collision of the cube and the wall that counted down to the destruction of the wall.

    Thanks in advance.

    • Hi there, thanks for the props! To trigger something on a collision you would simply call the timer to start when the collision occurs. How does that happen? well if you already control the timer with a boolean variable, you can simply tell the collision to set that variable to true for example. You should look at the tutorial on GetComponent or SendMessage if your timer exists in a separate script on another object. Good luck!

    First of all I’d like to say everything I know in Unity I have learnt here, so thank you very much for the invaluable tutorials. I’m trying to make a script to pause the timer when OnTriggerEnter and resume where it left off when OnTriggerExit. I’ve got the trigger and countdown timer working, I just have no idea how to pause/resume.

    Any hep would be greatly appreciated!

    • Hey there, just set up a boolean variable that your ontriggerenter / ontriggerexit toggles to true and false, and then only add to your timer if that var is set to true eg.

      if(boolean == true){
      add to timer here;
      }

      then it’ll only add then surely?

    I tried using the timer to destroy instances of the a created game object prefab by attaching the following script to the prefab.


    var bbtimer : float = 5.0;
    var SelectPrefab : GameObject;

    function Update () {

    if(bbtimer > 0){
    bbtimer -= Time.deltaTime;
    }
    if(bbtimer <= 0){
    Destroy(GameObject.SelectPrefab);
    }
    }

    This would successfully generate a new timer for every instantiated object, however it would not destroy the object.

    Thoughts?

  • Got it working!

    var bbtimer : float = 5.0;

    function Update () {

    if(bbtimer > 0){
    bbtimer -= Time.deltaTime;
    }
    if(bbtimer <= 0){
    Destroy(gameObject);
    }
    }

    This would be attached to the prefab being instantiated.

  • if(myTimer > 0){
    myTimer -= Time.deltaTime;
    What does -= mean?

    • just means ‘subtract’ because in code you don’t want to say simply ‘-’. += for add, and -= for subtract.

    I tried to make a script so I can create objects in defined amounts and time periods between each creation.

    var NewObject : GameObject;
    var AmountOfObjects : float = 1.0;
    var Timer : float = 0.5;
    function Start () {
    for (var i=0;i<AmountOfObjects;i++)
    {Instantiate(NewObject, transform.position, transform.rotation);
    yield WaitForSeconds(Timer);
    }

    }

  • hi guys,

    how would i link this into a GUI?

    ive tried this but it cant convert an int to a string…

    //A simple countdown timer
    var myTimer : int = 0;

    function Update () {
    if(myTimer > 0){
    myTimer -= Time.deltaTime;
    guiText.text = myTimer;
    }
    if(myTimer <= 0){
    Debug.Log("GAME OVER");

    guiText.text = "Game Over";
    }
    }

    cheers

    • you must simply add it to an empty string, so you’d use -
      guiText.text = “”+myTimer;

    Thank you for your help :)

Leave a Comment