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(){
   } else {
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;

I cant figure out where is the glitch?anyone? thanks,

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.)

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] );