Sometimes, we want a message to display just for a certain time, and then fade away and disappear.
Creating a message that fades away
Getting ready
This recipe adapts the previous one. So, make a copy of the project for the that recipe, and work on this copy.
How to do it...
To display a text message that fades away, follow these steps:
- In the Inspector panel, remove the scripted component, DigitalCountdown, from the Text-clock GameObject.
- 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; } }
- When you run the Scene, you will now see that the message on the screen slowly fades away, disappearing after five seconds.
How it works...
You added an instance of the FadeAway scripted class to the Text-hello GameObject. Due to the RequireComponent(...) attribute, an instance of the CountdownTimer script class was also automatically added.
The Awake() method caches references to the Text and CountdownTimer components in the countdownTimer and textUI variables.
The Start() method reset the countdown timer to start counting down from five seconds.
The Update() method (executed every frame) retrieves the proportion of time remaining in our timer by calling the GetProportionTimeRemaining() method. This method returns a value between 0.0 and 1.0, which also happens to be the range of values for the alpha (transparency) property of the color property of a UI Text game object.
It is often a good idea to represent proportions as values between 0.0 and 1.0. Either this will be just the value we want for something, or we can multiply the maximum value by our decimal proportion, and we get the appropriate value. For example, if we wanted the number of degrees of a circle for a given 0.0–0.1 proportion, we just multiply by the maximum of 360, and so on.
The Update() method then retrieves the current color of the text being displayed (via textUI.color), updates its alpha property, and resets the text object to have this updated color value. The result is that each frame in the text object's transparency represents the current value of the proportion of the timer remaining until it fades to fully transparent when the timer gets to zero.