Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Unity Cookbook
  • Toc
  • feedback
Unity Cookbook

Unity Cookbook

By : Matt Smith, Shaun Ferns, Sinéad Murphy
4.7 (27)
close
Unity Cookbook

Unity Cookbook

4.7 (27)
By: Matt Smith, Shaun Ferns, Sinéad Murphy

Overview of this book

Unleash your game development potential with Unity Cookbook, 5th Edition, designed to equip you with the skills and knowledge needed to excel in Unity game development. With over 160 expertly crafted recipes empowering you to pioneer VR and AR experiences, excel in mobile game development, and become a master of audio techniques. In this latest edition, we've meticulously curated a collection of recipes that reflect the latest advancements in Unity 2023, ensuring you stay at the forefront of game development. You'll discover dedicated recipes for First/Third Person (Core) templates, create engaging mobile games, delve into Virtual and Augmented Reality, and go further with audio by exploring advanced techniques. Additionally, the book has been fully updated to incorporate the new input system and TextMeshPro, essential elements for modern game development. From exploring C# scripting to crafting stylish UIs, creating stunning visual effects, and understanding shader development through Shader Graph, every chapter is designed to take you closer to your goal of becoming a proficient Unity developer. So, whether you're aiming to develop the next hit game, enhance your portfolio, or simply have fun building games, this book will be your trusted companion on your journey to Unity proficiency.
Table of Contents (22 chapters)
close
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.

bookmark search playlist download font-size

Change the font size

margin-width

Change margin width

day-mode

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Delete Bookmark

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete