Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Unity 5.x Cookbook

You're reading from   Unity 5.x Cookbook More than 100 solutions to build amazing 2D and 3D games with Unity

Arrow left icon
Product type Paperback
Published in Oct 2015
Publisher Packt
ISBN-13 9781784391362
Length 570 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Toc

Table of Contents (14) Chapters Close

Preface 1. Core UI – Messages, Menus, Scores, and Timers FREE CHAPTER 2. Inventory GUIs 3. 2D Animation 4. Creating Maps and Materials 5. Using Cameras 6. Lights and Effects 7. Controlling 3D Animations 8. Positions, Movement and Navigation for Character GameObjects 9. Playing and Manipulating Sounds 10. Working with External Resource Files and Devices 11. Improving Games with Extra Features and Optimization 12. Editor Extensions Index

Displaying a digital countdown timer

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

Displaying a digital countdown timer

Getting ready

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 1362_01_03 folder.

How to do it...

To create a digital countdown timer, follow these steps:

  1. In the Inspector panel, remove the scripted component, ClockDigital, from GameObject Text-clock.
  2. Create a DigitalCountdown C# script class containing the following code, and add an instance as a scripted component to GameObject Text-clock:
    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;
    using System;
    
    public class DigitalCountdown : MonoBehaviour {
      private Text textClock;
    
      private float countdownTimerDuration;
      private float countdownTimerStartTime;
    
      void Start (){
        textClock = GetComponent<Text>();
        CountdownTimerReset(30);
      }
    
      void Update (){
        // default - timer finished
        string timerMessage = "countdown has finished";
        int timeLeft = (int)CountdownTimerSecondsRemaining();
    
        if(timeLeft > 0)
          timerMessage = "Countdown seconds remaining = " + LeadingZero( timeLeft );
    
        textClock.text = timerMessage;
      }
    
      private void CountdownTimerReset (float delayInSeconds){
        countdownTimerDuration = delayInSeconds;
        countdownTimerStartTime = Time.time;
      }
    
      private float CountdownTimerSecondsRemaining (){
        float elapsedSeconds = Time.time - countdownTimerStartTime;
        float timeLeft = countdownTimerDuration - elapsedSeconds;
        return timeLeft;
      }
    
      private string LeadingZero (int n){
        return n.ToString().PadLeft(2, '0');
      }
    }
  3. 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.

How it works...

You added a Text GameObject to a scene. You have added an instance of the DigitalCountdown C# script class to that GameObject.

There is one variable, textClock, which will be a reference to the Text component, whose text content we wish to update in each frame with a time remaining message (or a timer complete message). Then, a call is made to the CountdownTimerReset(…) method, passing an initial value of 30 seconds.

The Start() method (executed when the scene begins) sets the textClock variable to find the Text component in the GameObject where our scripted object has been added.

The Update() method is executed in every frame. This method initially sets the timerMessage variable to a message, stating that the timer has finished (the default message to display). Then the seconds remaining are tested to be greater than zero. And if so, then the message variable has its contents changed to display the integer (whole) number of the seconds remaining in the countdown—retrieved from the CountdownTimerSecondsRemaining() method. This method finally updates the text property (that is, the letters and numbers that the user sees) to be a string with a message about the remaining seconds.

The CountdownTimerReset(…) method records the number of seconds provided, and the time the method was called.

The CountdownTimerSecondsRemaining() method returns an integer value of the number of seconds remaining.

You have been reading a chapter from
Unity 5.x Cookbook
Published in: Oct 2015
Publisher: Packt
ISBN-13: 9781784391362
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime