Displaying a digital countdown timer

Many games involve players completing tasks or getting bonus points within a set time. This recipe shows how to create a basic countdown timer, similar to the one shown in the following screenshot:

Displaying a digital countdown timer

How to do it...

To display a digital countdown timer, please follow this step:

  1. Attach the following C# script class to the Main Camera:
    // file: CountdownTimer.cs
    using UnityEngine;
    using System.Collections;
    
    public class CountdownTimer : MonoBehaviour {
      private float secondsLeft = 3f;
      
      private void OnGUI(){
        if( secondsLeft > 0)
          GUILayout.Label("Countdown seconds remaining = " + (int)secondsLeft	 );
        else
          GUILayout.Label("countdown has finished");
        
      }
      
      private void Update(){
        secondsLeft -= Time.deltaTime;
      }
    }

How it works...

Each secondsLeft frame is decremented by the time since the last frame (Time.deltaTime). When this variable goes below zero, the timer has finished. The value in the variable can be presented to the user as an integer through a simple cast statement, that is, (int) secondsLeft.

See also

  • The Displaying a countdown timer graphically (5, 4, 3, 2, 1 – blast off) recipe.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.56.12