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

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.

Flexible range of 0.0 1.0

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.