Fade out effect isn't working if loaded at the second time.

#pragma strict

 // FadeInOut
 
 var fadeTexture : Texture2D;
 var fadeSpeed = 0.2;
 var drawDepth = -1000;
 
 private var alpha = 1.0; 
 private var fadeDir = -1;

 function OnGUI()
 {  
     alpha += fadeDir * fadeSpeed * Time.deltaTime;  
     alpha = Mathf.Clamp01(alpha);   
     
     GUI.color.a = alpha;
     
     GUI.depth = drawDepth;
     
     GUI.DrawTexture(Rect(0, 0, Screen.width, Screen.height), fadeTexture);
 }

That’s my script that is attached on the Main Camera.
A plain black texture is attached to fadeTexture.

This works whenever I start the game from the main menu. But when I start a level and I click a button where it takes me back to the main menu, the “fade out” effect doesn’t work anymore, the plain black picture is just there. Covering the whole GUI.

I have two different scenes.
Main Menu and the level of the game.

Advanced thank you guys!

EDIT: By the way, for my BackToMainMenu script. I use

Application.LoadLevel(0);

I think the culprit is this line:

alpha += fadeDir * fadeSpeed * Time.deltaTime; 

The first time it works fine but second time it doesn’t because ‘alpha’ retains its previous value. Every time you want fade out you need to reset the the value of ‘alpha’. Try to reset it and check it then if its working or not.

Call the fadeOut() function on the UI button you use to go back to the menu.

public var fadeOutTexture : Texture2D;
    public var fadeSpeed = 0.3;
     
    var drawDepth = -1000;
     
     
    private var alpha = 1.0; 
     
    private var fadeDir = -1;
    
    function Start(){
    	alpha=1;
    	fadeIn();
    } 
    
    function OnGUI(){
     
    	alpha += fadeDir * fadeSpeed * Time.deltaTime;	
    	alpha = Mathf.Clamp01(alpha);	
     
    	GUI.color.a = alpha;
     
    	GUI.depth = drawDepth;
     
    	GUI.DrawTexture(Rect(0, 0, Screen.width, Screen.height), fadeOutTexture);
    }
      
    function fadeIn(){
    	fadeDir = -1;	
    }
      
    function fadeOut(){
    	fadeDir = 1;	
    }