Often, we want to show the user a message briefly, and then have that message disappear. A nice way to do this is to have the message fade away, and then destroy itself when is it no longer visible. The following screenshot is an example of such a message:
To display a message that fades away, please follow these steps:
GUIText
object, position it and change the font size and text as desired.GUIText
object:// file: FadingMessage using UnityEngine; using System.Collections; public class FadingMessage : MonoBehaviour { const float DURATION = 2.5f; private void Update() { if( Time.time > DURATION){ Destroy(gameObject); } Color newColor = guiText.material.color; float proportion = (Time.time / DURATION); newColor.a = Mathf.Lerp(1, 0, proportion); guiText.material.color = newColor; } }
The DURATION
constant defines the number of seconds the image is to be visible for. Once the scene has been running for this many seconds, the parent game object is destroyed. Dividing the elapsed time by DURATION
gives the proportion of the life for this fading message (between 0.0 and 1.0). The Mathf.Lerp()
method takes such a proportion as its third argument, and gives the corresponding value scaled between the first and second arguments—in this case, we wish to lerp from 1 (full alpha visibility) to 0 (invisible). This alpha value is assigned to a copy of the guiText
material's color, and then this new color object is reassigned to the guiText
object's material.
Here are some details you don't want to miss:
By creating a prefab, and placing a copy of the GUIText
object with this script attached, messages can be easily created as required by the main game manager. Assuming that the fadingMessagePrefab
public variable has been assigned a value of the prefab via the Inspector view, then the following method could be called whenever a fading message is required. This will then create an instance of the GUIText
prefab and sets its text property to whatever message is passed in to the method:
private void CreateMessage(string message) { GameObject fadingMessageGO = (GameObject)Instantiate(fadingMessagePrefab); fadingMessageGO.guiText.text = message; }
Another strategy is to have a single GUIText
object always present in the scene, but not always visible. Each time a message is to be displayed to the user, the new text is set and the alpha is set back to 1 (or its desired starting value), and then it will start fading again.
3.129.218.69