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 Cookbook

You're reading from   Unity Cookbook Over 160 recipes to craft your own masterpiece in Unity 2023

Arrow left icon
Product type Paperback
Published in Nov 2023
Publisher Packt
ISBN-13 9781805123026
Length 780 pages
Edition 5th Edition
Languages
Tools
Arrow right icon
Authors (3):
Arrow left icon
Sinéad Murphy Sinéad Murphy
Author Profile Icon Sinéad Murphy
Sinéad Murphy
Matt Smith Matt Smith
Author Profile Icon Matt Smith
Matt Smith
Shaun Ferns Shaun Ferns
Author Profile Icon Shaun Ferns
Shaun Ferns
Arrow right icon
View More author details
Toc

Table of Contents (22) Chapters Close

Preface 1. Displaying Data with Core UI Elements 2. Responding to User Events for Interactive UIs FREE CHAPTER 3. Inventory and Advanced UIs 4. Playing and Manipulating Sounds 5. Textures, Materials, and 3D Objects 6. Creating 3D Environments with Terrains 7. Creating 3D Geometry with ProBuilder 8. 2D Animation and Physics 9. Animated Characters 10. Saving and Loading Data 11. Controlling and Choosing Positions 12. Navigation Meshes and Agents 13. Cameras, Lighting, and Visual Effects 14. Shader Graphs and Video Players 15. Particle Systems and Other Visual Effects 16. Mobile Games and Applications 17. Augmented Reality (AR) 18. Virtual and Extended Reality (VR/XR) 19. Advanced Topics – Gizmos, Automated Testing, and More 20. Other Books You May Enjoy
21. Index

Displaying a countdown timer graphically with a UI Slider

There are many cases where we wish to inform the player of how much time is left in a game or how much longer an element will take to download – for example, a loading progress bar, the time or health remaining compared to the starting maximum, or how much the player has filled up their water bottle from the fountain of youth.

In this recipe, we’ll illustrate how to remove the interactive “handle” of a UI Slider, and then change the size and color of its components to provide us with an easy-to-use, general-purpose progress/proportion bar:

A screenshot of a computer

Description automatically generated

Figure 2.20: Example of a countdown timer with a UI Slider

In this recipe, we’ll use our modified UI Slider to graphically present to the user how much time remains on a countdown timer.

Getting ready

For this recipe, we have prepared the script and images that you need in the 02_04 folder, respectively named _Scripts and Images.

How to do it...

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

  1. Create a new Unity 2D project and install TextMeshPro by choosing: Window | TextMeshPro | Import TMP Essential Resources.
  2. Import the CountdownTimer script and the red_square and green_square images into this project.
  3. Add a UI Text(TMP) GameObject to the scene with a Font size of 30 and placeholder text such as a UI Slider value (this text will be replaced with the slider value when the scene starts). Check that Overflow is set to Overflow.
  4. In the Hierarchy window, add a Slider GameObject to the scene by going to GameObject | UI | Slider.
  5. In the Inspector window, modify the settings for the position of the Slider GameObject’s Rect Transform to the top-center part of the screen.
  6. Ensure that the Slider GameObject is selected in the Hierarchy window.
  7. Deactivate the Handle Slide Area child GameObject (by unchecking it).
  8. You’ll see the “drag circle” disappear in the Game window (the user will not be dragging the slider since we want this slider to be display-only):
A screenshot of a computer

Description automatically generated

Figure 2.21: Ensuring Handle Slide Area is deactivated

  1. Select the Background child and do the following:
    • Drag the red_square image into the Source Image property of the Image component in the Inspector window.
  2. Select the Fill child of the Fill Area child and do the following:
    • Drag the green_square image into the Source Image property of the Image component in the Inspector window.
  3. Select the Fill Area child and do the following:
    • In the Rect Transform component, use the Anchors preset position of left-middle.
    • Set Width to 155 and Height to 12:

Figure 2.22: Selections in the Rect Transform component

  1. Create a C# script class called SliderTimerDisplay that contains the following code and add an instance as a scripted component to the Slider GameObject:
    using UnityEngine;
    using UnityEngine.UI;
    using TMPro;
    [RequireComponent(typeof(CountdownTimer))]
    public class SliderTimerDisplay : MonoBehaviour {
       private CountdownTimer countdownTimer;
       private Slider sliderUI;
       void Awake() {
             countdownTimer = GetComponent<CountdownTimer>();
             sliderUI = GetComponent<Slider>();
       }
       void Start() {
             SetupSlider();
             countdownTimer.ResetTimer( 30 );
       }
       void Update () {
             sliderUI.value = countdownTimer.GetProportionTimeRemaining();
             print (countdownTimer.GetProportionTimeRemaining());
       }
       private void SetupSlider () {
             sliderUI.minValue = 0;
             sliderUI.maxValue = 1;
             sliderUI.wholeNumbers = false;
       }
    }
    

Run your game. 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...

In this recipe, you hid the Handle Slide Area child so that the UI Slider is for display only, which means it cannot be interacted with by the user. The Background color of the UI 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 property of the UI Slider was set to green so that the proportion remaining is displayed in green – the more green that’s displayed, the greater the value of the slider/timer.

An instance of the provided CountdownTimer script class was automatically added as a component to the UI Slider via [RequireComponent(...)].

The Awake() method caches references to the CountdownTimer and Slider components in the countdownTimer and sliderUI variables.

The Start() method calls the SetupSlider() method and then resets the countdown timer so that it starts counting down from 30 seconds.

The SetupSlider() method sets up this slider for float (decimal) values between 0.0 and 1.0.

In each frame, the Update() method sets the slider value to the float that’s returned by calling the GetProportionRemaining() method from the running timer. At runtime, Unity adjusts the proportion of red/green that’s displayed in the UI Slider so that it matches the slider’s value.

You have been reading a chapter from
Unity Cookbook - Fifth Edition
Published in: Nov 2023
Publisher: Packt
ISBN-13: 9781805123026
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