Unity 2018 Cookbook(Third Edition)
上QQ阅读APP看书,第一时间看更新

How to do it...

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

  1. Create a new 2D project.
  2. Import the CountdownTimer script and the red_square and green_square images to this project.
  3. Add a UI Text GameObject to the scene with a Font size of 30 and placeholder text such as UI Slider value here (this text will be replaced with the slider value when the scene starts). Set Horizontal- and Vertical- Overflow to Overflow.
  4. In the Hierarchy, add a Slider GameObject to the scene  choose menu: GameObject | UI | Slider.
  5. In the Inspector, modify the settings for the Position of the Slider GameObject's Rect Transform to the top-middle part of the screen.
  6. Ensure that the Slider GameObject is selected in the Hierarchy.
  7. Deactivate the Handle Slide Area child GameObject (by unchecking it)
  8. 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):
  1. Select the Background child:
    • Drag the red_square image into the Source Image property of the Image (Script) component in the Inspector
  2. Select the Fill child of the Fill Area child:
    • Drag the green_square image into the Source Image property of the Image (Script) component in the Inspector
  3. 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:
  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; 

[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 and you will see the slider move with each second, revealing more and more of the red background to indicate the time remaining.