
上QQ阅读APP看书,第一时间看更新
How to do it...
To create a digital countdown timer, follow these steps:
- Import the provided _Scripts folder.
- In the Inspector panel, remove the scripted component, ClockDigital, from the Text-clock GameObject.
- In the Inspector panel, add an instance of the CountdownTimer script class as a component by clicking the Add Component button, selecting Scripts, and choosing the CountdownTimer script class.
- Create a DigitalCountdown C# script class that contains the following code, and add an instance as a scripted component to the Text-clock GameObject:
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; } } }
- When you run the Scene, you will now see a digital clock counting down from 30. When the countdown reaches zero, the message countdown has finished will be displayed.
Automatically add components with [RequireComponent(...)]
The DigitalCountdown script class requires the same GameObject to also have an instance of the CountdownTimer script class. Rather than having to manually attach an instance of a require script, you can use the [RequireComponent(...)] C# attribute immediately before the class declaration statement. This will result in Unity automatically attaching an instance of the required script class.
The DigitalCountdown script class requires the same GameObject to also have an instance of the CountdownTimer script class. Rather than having to manually attach an instance of a require script, you can use the [RequireComponent(...)] C# attribute immediately before the class declaration statement. This will result in Unity automatically attaching an instance of the required script class.
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 {
Learn more from the Unity documentation at https://docs.unity3d.com/ScriptReference/RequireComponent.html.