- Home /
FadeIn/FadeOut the GUI
I'm trying to fade In my GUI on start and fade out when a button is clicked. I've tried to call my fade in and fade out functions in the both OnGUI and Update. What happens is the fade In works good, but when the button which to fade out the GUI is pressed the GUI suddenly disappears than means directly from 1 to 0 and not gradually.
Here is my code:
var showGUI:boolean = true; var alpha:float;
function Update(){ if(showGUI){ FadeIn(); } else { FadeOut(); } } function FadeOut(){ alpha = Mathf.Lerp(1,0,Time.time*0.5); }
function FadeIn(){ alpha = Mathf.Lerp(0,1,Time.time*0.5); }
function OnGUI(){ GUI.color.a = alpha; if(GUI.Button(Rect(0,0,100,20),"FadeOutGUI"){ showGUI=false; } }
I cant figure out where is the glitch?anyone? thanks,
Answer by Jesse Anders · Oct 05, 2010 at 04:44 PM
The t argument to Mathf.Lerp() is clamped to the range [0, 1], and Time.time is the time in seconds since the game was started.
I assume you're observing the fade-in immediately after starting the game. If so, the fade-in is working because over the first two seconds of the game, Time.time falls within the range [0, 2] and therefore t falls within the range [0, 1], and so the effect is as expected.
However, Time.time will continue to increase steadily after that; after 2 seconds, Time.time*0.5 will always be greater than 1, and therefore the t argument will always be 1. As such, Mathf.Lerp(1,0,Time.time*0.5) will generally always return 0, which means the fade out will be instant.
To get the right effect, you'll want to use some other timing method. You could handle the timing manually, or you could use coroutines, I imagine. Also, if you adjust the alpha by applying a velocity (by which I simply mean a signed delta) over time, it might better handle the case where the user clicks on the 'fade out' button before the fade-in has completed. (In this case, ideally, the fade-out would begin at the current alpha rather than at alpha = 1.)
Yep, true, here is what i tweaked:
function FadeOut(){ alpha = $$anonymous$$athf.Lerp(alpha,0,Time.deltaTime*5); }
and it works just fine. thanks a lot!
Answer by dentedpixel · Apr 26, 2013 at 11:40 AM
I added alpha support to my animation engine LeanTween to cut down on that mess of functions you have to write to achieve something as simple as fading a button.
Here is the same result with much less code:
var buttonRect3:LTRect = new LTRect(0.0, 0.0, 200, 100 );
function OnGUI(){
if(GUI.Button(buttonRect3.rect, "Alpha")){
LeanTween.alpha( buttonRect3, 0.0, 1.0, ["ease",LeanTweenType.easeOutQuad] );
}
}
[2]: http://dentedpixel.com/developer-diary/rotate-and-fade-gui-elements-in-unity3d-with-leantween/
Your answer
Follow this Question
Related Questions
making a fadeout with the new GUI in 4.6? 3 Answers
Is there anyway to fade in/out a GUI image without using an addon/asset? 2 Answers
fade between scenes? 1 Answer
Fade in from black 4 Answers
How to make 3D Text fade in and out? 3 Answers