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 countdown timer graphically with a UI Slider

There are many cases where we wish to inform the player of the proportion of time remaining, or at the completion of some value at a point in time, for example, a loading progress bar, the time or health remaining compared to the starting maximum, how much the player has filled up their water bottle from the fountain of youth, and so on. In this recipe, we'll illustrate how to remove the interactive 'handle' of a UI Slider, and change the size and color of its components to provide us with an easy-to-use, general purpose progress/proportion bar. In this recipe, we'll use our modified slider to graphically present to the user how much time remains for a countdown timer.

Displaying a countdown timer graphically with a UI Slider

Getting ready

This recipe adapts the previous one. So, make a copy of the project for the previous recipe, and work on this copy to follow this recipe.

For this recipe, we have prepared the script and images that you need in the folders named Scripts and Images in the 1362_01_10 folder.

How to do it...

To create a digital countdown timer with a graphical display, follow these steps:

  1. Delete the Text GameObject.
  2. Import the CountdownTimer script and the red_square and green_square images to this project.
  3. Ensure that the Slider GameObject is selected in the Hierarchy tab.
  4. Deactivate the Handle Slide Area child GameObject (by unchecking it)
  5. You'll see the "drag circle" disappear in the Game panel (the user will not be dragging the slider, since we want this slider to be display-only), as shown in the following screenshot:
    How to do it...
  6. Select the Background child:
    • Drag the red_square image into the Source Image property of the Image (Script) component in the Inspector view
  7. Select the Fill child:
    • Drag the green_square image into the Source Image property of the Image (Script) component in the Inspector tab
  8. Select the Fill Area child:
    • In the Rect Transform component, use the Anchors preset position of left-middle
    • Set Width to 155 and Height to 12, as shown here:
    How to do it...
  9. Ensure that the Slider GameObject is selected in the Hierarchy. Then, attach an instance of C# script class called CountdownTimer as a component of this GameObject.
  10. Create a C# script class called SliderTimerDisplay containing the following code, and add an instance as a scripted component to the Slider GameObject:
    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;
    
    public class SliderTimerDisplay : MonoBehaviour {
      private CountdownTimer countdownTimer;
      private Slider sliderUI;
      private int startSeconds = 30;
    
      void Start (){
        SetupSlider();
        SetupTimer();
      }
    
      void Update () {
        sliderUI.value = countdownTimer.GetProportionTimeRemaining();
        print (countdownTimer.GetProportionTimeRemaining());
      }
    
      private void SetupSlider (){
        sliderUI = GetComponent<Slider>();
        sliderUI.minValue = 0;
        sliderUI.maxValue = 1;
        sliderUI.wholeNumbers = false;
      }
    
      private void SetupTimer (){
        countdownTimer = GetComponent<CountdownTimer>();
        countdownTimer.ResetTimer(startSeconds);
      }
    }
  11. Run your game and you will see the slider move with each second, revealing more and more of the red background to indicate the time remaining.

How it works...

You hid the Handle Slide Area child so that Slider is for display only, and cannot be interacted with by the user. The Background color of the Slider was set to red, so that, as the counter goes down, more and more red is revealed—warning the user that the time is running out. The Fill of the Slider was set to green, so that the proportion remaining is displayed in green (the more green it becomes, the larger the value of the slider/timer).

An instance of the provided CountdownTimer script class was added as a component to the Slider. The ResetTimer(…) method records the number of seconds provided and the time the method was called. The GetProportionRemaining() method returns a value from 0.0-1.0, representing the proportion of the seconds remaining (1.0 being all seconds, 0.5 half the seconds, and 0.0 meaning that no seconds are left).

You have added to the Slider GameObject an instance of the SliderTimerDisplay scripted class. The Start() method calls the SetupSlider() and SetupTimer() methods.

The SetupSlider() method sets the sliderUI variable to be a reference to the Slider component, and sets up this slider mapped to float (decimal) values between 0.0 and 1.0.

The SetupTimer() method sets the countdownTimer variable to be a reference for the CountdownTimer component, and starts this timer scripted component to count down from 30 seconds.

In each frame, the Update()method sets the slider value to the float returned by calling the GetProportionRemaining()method from the running timer.

Note

Try to work with floats between 0.0-1.0 whenever possible.

Integers could have been used, setting the Slider min to 0 and max to 30 (for 30 seconds). However, changing the total number of seconds would then also require the Slider settings to be changed. In most cases working with a float proportion between 0.0 and 1.0 is the more general-purpose and reusable approach to adopt.

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 $19.99/month. Cancel anytime