Creating a message that fades away
Sometimes, we want a message to display just for a certain time, and then fade away and disappear, which will appear as shown in this screenshot:
Getting ready
This recipe adapts the first recipe in this chapter, so make a copy of that project to work on for this recipe.
For this recipe, we have prepared the script that you need in a folder named Scripts
in the 1362_01_04
folder.
How to do it...
To display a text message that fades away, follow these steps:
- Import the provided C# script class called
CountdownTimer
. - Ensure that GameObject Text-hello is selected in the Hierarchy tab. Then, attach an instance of the
CountdownTimer
C# script class as a component of this GameObject. - Create a C# script class,
FadeAway
, containing the following code, and add an instance as a scripted component to the GameObject Text-hello:using UnityEngine; using System.Collections; using UnityEngine.UI; public class FadeAway : MonoBehaviour { private CountdownTimer countdownTimer; private Text textUI; private int fadeDuration = 5; private bool fading = false; void Start (){ textUI = GetComponent<Text>(); countdownTimer = GetComponent<CountdownTimer>(); StartFading(fadeDuration); } void Update () { if(fading){ float alphaRemaining = countdownTimer.GetProportionTimeRemaining(); print (alphaRemaining); Color c = textUI.material.color; c.a = alphaRemaining; textUI.material.color = c; // stop fading when very small number if(alphaRemaining < 0.01) fading = false; } } public void StartFading (int timerTotal){ countdownTimer.ResetTimer(timerTotal); fading = true; } }
- When you run the scene, you will now see that the message on the screen slowly fades away, disappearing after 5 seconds.
How it works...
An instance of the provided CountdownTimer
script class was added as a component to the GameObject Text-hello.
You added to the GameObject Text-hello an instance of the scripted class, FadeAway
. The Start()
method caches references to the Text
and CountdownTimer
components in the countdownTimer
and textUI
variables. Then, it calls the StartFading(…)
method, passing in the number 5, so that the message will have faded to invisible after 5 seconds.
The StartFading(…)
method starts this timer scripted component to countdown to the given number of seconds. It also sets the fading
Boolean flag variable to true
.
The Update()
method, in each frame, tests if the fading
variable is true
. If it is true, then the alpha (transparency) component of the color of the Text-hello object is set to a value between 0.0 and 1.0, based on the proportion of the time remaining in the CountdownTimer
object. Finally, if the proportion of time remaining is less than a very small value (0.01), then the fading
variable is set to false
(to save the processing work since the text is now invisible).