Timers can have more effects when displayed graphically. This recipe illustrates a simple way to display a rocket ship-style countdown, using images for each second (5, 4, 3, 2, 1) and a final image for the "blast off". The following screenshot shows an example of this:
If you need a set of images for this recipe; you'll find a series of PNG images in the 0423_04_08
folder.
To display a countdown timer graphically, please follow these steps:
// file: CountdownGraphical.cs using UnityEngine; using System.Collections; public class CountdownGraphical : MonoBehaviour { public Texture2D imageDigit1; public Texture2D imageDigit2; public Texture2D imageDigit3; public Texture2D imageDigit4; public Texture2D imageDigit5; public Texture2D imageBlastOffText; private int countdownTimerDelay; private float countdownTimerStartTime; void Awake(){ CountdownTimerReset( 5 ); } void OnGUI(){ GUILayout.Label( CountdownTimerImage() ); } void CountdownTimerReset(int delayInSeconds){ countdownTimerDelay = delayInSeconds; countdownTimerStartTime = Time.time; } int CountdownTimerSecondsRemaining(){ int elapsedSeconds = (int)(Time.time - countdownTimerStartTime); int secondsLeft = (countdownTimerDelay - elapsedSeconds); return secondsLeft; } Texture2D CountdownTimerImage(){ switch( CountdownTimerSecondsRemaining() ){ case 5: return imageDigit5; case 4: return imageDigit4; case 3: return imageDigit3; case 2: return imageDigit2; case 1: return imageDigit1; default: return imageBlastOffText; } } }
An alternative method of implementing a countdown timer algorithm is presented in this recipe (whereby the countdown progress is measured by comparing the current elapsed seconds (Time.time
) against the time when the timer was started—countdownTimerStartTime
).
In this recipe, the OnGUI()
method displays a label with the image returned from the CountdownTimerImage()
method. This method uses a switch
statement to return the corresponding image to the current number of seconds remaining. Six images are public variables, and so can be set via the Inspector.
3.15.168.214