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

How to do it...

To display a text message that fades away, follow these steps:

  1. In the Inspector panel, remove the scripted component, DigitalCountdown, from the Text-clock GameObject.
  2. Create a C# script class, FadeAway, that contains the following code, and add an instance as a scripted component to the Text-hello GameObject:
using UnityEngine; 
using UnityEngine.UI; 

[RequireComponent (typeof (CountdownTimer))] 
public class FadeAway : MonoBehaviour { 
   private CountdownTimer countdownTimer; 
   private Text textUI; 

   void Awake () { 
         textUI = GetComponent<Text>();       
         countdownTimer = GetComponent<CountdownTimer>(); 
   } 

   void Start(){ 
         countdownTimer.ResetTimer( 5 ); 
   } 

   void Update () { 
         float alphaRemaining = 
countdownTimer.GetProportionTimeRemaining(); print (alphaRemaining); Color c = textUI.color; c.a = alphaRemaining; textUI.color = c; } }
  1. When you run the Scene, you will now see that the message on the screen slowly fades away, disappearing after five seconds.