This recipe will show you how to display a digital countdown clock, as shown here:

This recipe will show you how to display a digital countdown clock, as shown here:
This recipe adapts the previous one. So, make a copy of the project for the previous recipe, and work on this copy.
For this recipe, we have prepared the script that you need in a folder named _Scripts in the 01_03 folder.
To create a digital countdown timer, follow these steps:
using UnityEngine; using UnityEngine.UI; public class DigitalCountdown : MonoBehaviour { private Text textClock; private CountdownTimer countdownTimer; void Awake() { textClock = GetComponent<Text>(); countdownTimer = GetComponent<CountdownTimer>(); }
void Start() { countdownTimer.ResetTimer( 30 ); } void Update () { int timeRemaining = countdownTimer.GetSecondsRemaining(); string message = TimerMessage(timeRemaining); textClock.text = message; } private string TimerMessage(int secondsLeft) { if (secondsLeft <= 0){ return "countdown has finished"; } else { return "Countdown seconds remaining = " + secondsLeft; } } }
For example, by writing the following, Unity will add an instance of CountdownTimer as soon as an instance of the DigitalCountdown script class has been added as a component of a GameObject:
using UnityEngine; using UnityEngine.UI; [RequireComponent (typeof (CountdownTimer))] public class DigitalCountdown : MonoBehaviour {
You have added instances of the DigitalCountdown and CountdownTimer C# script classes to your scene's UI Text GameObject.
The Awake() method caches references to the Text and CountdownTimer components in the countdownTimer and textClock variables. The textClock variable will be a reference to the UI Text component, whose text content we wish to update in each frame with a time-remaining message (or a timer-complete message).
The Start() method calls the countdown timer object's CountdownTimerReset(...) method, passing an initial value of 30 seconds.
The Update() method is executed in every frame. This method retrieves the countdown timer seconds remaining and stores this value as an integer (whole number) in the timeRemaining variable. This value is passed as a parameter to the TimerMessage() method, and the resulting message is stored in the string (text) variable message. This method finally updates the text property (that is, the letters and numbers that the user sees) of the textClock UI Text GameObject to equal to the string message about the remaining seconds.
The TimerMessage() method takes an integer as input, and if the value is zero or less, a message stating the timer has finished is returned. Otherwise (if greater than zero seconds remain) a message stating the number of remaining seconds is returned.