Creating count down timer in unity by c# script

 In many cases in game we have to show count down timer. in this post i will explain how to create a timer which show a timer 3... 2.... 1.....  . so first create a simple basic gameObjects :-

1. Create a new scene in your unity project.
2. Create a UI text GameObject in your scene. as I have created and named as "timer text". and set text size, position, font, color of text etc according to you need.
3. Create a new C# script. I named it as "timer". always take care that your C# script name and class name should be same.
4. Create an other empty GameObject. I named it as "timer script". and attach C# timer script with it.
5. Now open timer C# script. Add UnityEngine.UI namespace so that we can use UI component and declare a text and float of name "timer_txt" and "t". You can use any name whatever you want. I just wrote these names so that you can understand which name i have used.
6.drag and drop timer text ui gameObject into it.  

C# count down timer


there are two method by which we can create a timer  so lets take a look at both method

First Method :- Using Time.deltaTime

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

public class timer : MonoBehaviour
{
    [SerializeFieldprivate Text timer_txt;
    private float t=4;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if(t>1)
        {
            t-=Time.deltaTime;
            int count=(int)t;
            timer_txt.text=count.ToString();
            if(t<=1)
            {
                Debug.Log("Count down completed");//here you can perform your task
            }
        }
        
    }
}

1. add  using UnityEngine.UI; i
2. [SerializeField] is used to show private declare variable in inspect window.
3. We have declare a float t and initialize it and gave value 4. 
4. in update method we use if(t>1) method so that inside code only run when t > 1 .
5. t-=Time.deltaTime; decrease the value of t at every update () fuction run. We have taken the value of t = 4 because when update function run first time it decrease the value of t from 4 to 3.xx and we change it to int so it become 3.
6. int count=(int)t;  change float value of t to int and assign it into count.
7. timer_txt.text=count.ToString(); timer_txt reference to the text UI gameObject and .text access
its text and ToString() fuction change count into string then add it to text. alternatively for reference to text ui gameObject you can declare GameObject and access text by calling GetComponent method in start() function.
8. in last if(t<=1) function you can use to perform your task whatever you want to do like you want start your game or changing tern or something else.

Second Method : - Using WaitForSeconds( ) 

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

public class timer : MonoBehaviour
{
    [SerializeFieldprivate Text timer_txt;
    private float t=4;
    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(count_down_fn());
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    IEnumerator count_down_fn()
    {
        yield return new WaitForSeconds(1f);
        t-=1;
        int count=(int)t;
        timer_txt.text=count.ToString();
        if(t<=0)
        {
            Debug.Log("Count down completed");//here you can perform yourtask
        }
        else
        {
            StartCoroutine(count_down_fn());
        }
    }


}


1. We need to write a IEnumerator function named count_down_fn() and we can call WaitForSeconds() fuction in its yield return type we can put float value of time in sceconds in this function.
2. All other code written after WaitForSeconds() fuction. run after the time written in it passed.
3. All code of showing timer and task to do after time is same. We also added an else statement so that the value of t is not 0 then again run Coroutine fuction.
4. Use StartCoroutine(count_down_fn());  where you want to run your time because IEnumerator always run in StartCoroutine function. 
5. Always take care that Coroutine should not run countinuosly like if you run it in update method and run at each frame then Unity Editor may crash or freeze.  when you run Coroutine take care it only run once or a definite time interval that's why we call second time coroutine function in else statement.

Use case of both method

You can use both method for creating a timer but there are some cases in which one is more useful then other so lets take a look at both 

Time.deltaTime Method : - It is most useful when your game have a mission to complete in a given time because if you pause game and change TimeScale = 0 then time counter will stop it help player it pausing game. if you use coroutine with WaitForSeconds method then it will also work same.        

Coroutine Method :- WaitForSecond() work same as Time.deltaTime but if you want to countine run timer even if timeScale is 0 then you have to use yield return new WaitForSecondsRealtime(1f) in place of WaitForSeconds(1f);
This is useful in games where you show countdown timer at game startup and you pause your game.

I hove you understand both method and there use try out both method and create a timer.

Popular posts from this blog

Positioning GameObjects in unity editor

Changing Image in unity by C# script