Book Image

Unity 5.x Cookbook

Book Image

Unity 5.x Cookbook

Overview of this book

Unity 5 is a flexible and intuitive multiplatform game engine that is becoming the industry's de facto standard. Learn to craft your own 2D and 3D computer games by working through core concepts such as animation, audio, shaders, GUI, lights, cameras, and scripting to create your own games with one of the most important and popular engines in the industry. Completely re-written to cover the new features of Unity 5, this book is a great resource for all Unity game developers, from those who have recently started using Unity right up to game development experts. The first half of the book focuses on core concepts of 2D game design while the second half focuses on developing 3D game development skills. In the first half, you will discover the new GUI system, the new Audio Mixer, external files, and animating 2D characters in 2D game development. As you progress further, you will familiarize yourself with the new Standard Shaders, the Mecanim system, Cameras, and the new Lighting features to hone your skills towards building 3D games to perfection. Finally, you will learn non-player character control and explore Unity 5's extra features to enhance your 3D game development skills.
Table of Contents (20 chapters)
Unity 5.x Cookbook
Credits
Foreword
About the Authors
About the Reviewers
www.PacktPub.com
Preface
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.

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:

  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:

  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.