How to create a simple countdown Timer in Unity

How to make a timer (countdown Clock from 60) as you see in the GIF below:

First you need to create a new Object on the canvas. Choose from the Menu:

GameObject -> UI ->Text

Than remove the “New Text” from the Inspector where the window is labeled “Text”. If you want you can change the size of the font in Inspector by changing the value “Font Size”.

To your object in Unity add a new script called: “Countdown”.

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

public class CountDown : MonoBehaviour {

  public int timeLeft = 60; //Seconds Overall
  public Text countdown; //UI Text Object

  void Start () {
    StartCoroutine("LoseTime");
    Time.timeScale = 1; //Just making sure that the timeScale is right
  }

  void Update () {
    countdown.text = ("" + timeLeft); //Showing the Score on the Canvas
  }

  //Simple Coroutine
  IEnumerator LoseTime()
  {
    while (true) {
      yield return new WaitForSeconds (1);
      timeLeft--; 
    }

  }}

Don’t forget to add the Text object to our script too!

 

You can change the Font too. In the gif example we used different one, than the standard Arial font.

Other tutorials in the series:

How to make the objects fall in Unity

Making Objects Fall Random On The Screen in Unity

How to Speed Up (Increase Speed) Time in Unity

Leave a Reply

Your email address will not be published. Required fields are marked *