I have a label in my GUI.Window and I need it to fade in/out. I’ve found many examples how to fade labels that are simply created in OnGUI() function. But they don’t solve my problem. So, is there any solution how to fade in/out a GUI.Label in GUI.Window? Here is the code I tried to use:
private Color myColor;
private float alpha = 1f;
void Update() {
if (Input.GetKeyUp(KeyCode.RightArrow)) {
while (alpha >= 0) {
alpha -= Time.deltaTime*0.3f;
}
void OnGUI () {
window = GUI.Window (0, window, pauseWindow, "");
}
void pauseWindow (int windowID) {
myColor = GUI.color;
myColor.a = alpha;
GUI.color = myColor;
GUI.label = (new Rect(100,100,100,100), "Fading Text");
myColor.a = 1f;
GUI.color = myColor;
GUI.label (new Rect (100,200,100,100), "Simple Text");
}
Your fading code will cause the alpha to reach 0 in a single frame.
You start a loop that fades the alpha value however you never actually break out of the loop until the value is 0. You are blocking unity from continuing until you exit your Update loop.
Try this:
public class Fade : MonoBehaviour
{
private Color myColor;
private float alpha = 1f;
private float speed = 1;
private float targetAlpha = 1;
void Update()
{
if( Input.GetKeyDown( KeyCode.RightArrow ) )
{
Debug.Log( "Fading Out" );
targetAlpha = 0;
}
if( Input.GetKeyDown( KeyCode.LeftArrow ) )
{
Debug.Log( "Fading In" );
targetAlpha = 1;
}
if( !Mathf.Approximately( alpha, targetAlpha ) )
{
alpha = Mathf.MoveTowards( alpha, targetAlpha, speed * Time.deltaTime );
}
}
void OnGUI ()
{
GUI.Window(0, new Rect( 10, 10, 300, 300 ), pauseWindow, "");
}
void pauseWindow (int windowID)
{
myColor = GUI.color;
myColor.a = alpha;
GUI.color = myColor;
GUI.Label(new Rect(100,100,100,100), "Fading Text");
myColor.a = 1f;
GUI.color = myColor;
GUI.Label(new Rect (100,200,100,100), "Simple Text");
}
}