How to make a scene fade out AFTER A FEW SECONDS?

So here’s what I’m trying to do. I have a basic scene acting as a cutscene, and after twentyish seconds, it finishes and loads a new scene; the level. The contents are identical, except that the cutscene one, the camera cannot be moved by the player. Pretty simple premise. This is a nice way to make it so that my non-existent coding skills don’t get in the way of messing up the scene.

I was trying to make it look neater… and I made the level scene fade in successfully. Likewise, I want to make the cutscene scene fade out when the time is up. I found a nice code that fades out perfectly, but it does so immediately. Here it is;

 #pragma strict
 
 // FadeInOut
 
 var fadeTexture : Texture2D;
 var fadeSpeed = 0.2;
 var drawDepth = -1000;
 
 private var alpha = 0.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);
 }

I want the script to wait for about three or four seconds BEFORE fading.

I can’t put in a yeild WaitForSeconds because its a coroutine, …or something like that.

So I need to make the script called at a later time, or activated by something else, or something. I don’t know enough about coding to know what to do. A little help? Thanks.

You need to wrap the content of your OnGUI() function inside an if statement with a boolean. As long as the boolean is false, OnGUI does nothing, when it turns to true, OnGUI starts the fading process.

If you don’t wanna use Coroutines, it’s doable with the Update function:

You need a couple more variables:

var fadeBool : boolean = false;
var timer : float = 0;
var secsToWait : float = 5; //number of seconds you want to wait before fading

You need an Update function that will increment your timer until you reach the number of seconds you want to wait before fade and then allow the fading:

function Update () {
   if (timer < secsToWait){
      timer += Time.deltaTime; //adds the time between two frames to the timer
   } else {
      fadeBool = true;
   }
}

Then you have to modify your OnGUI function:

function OnGUI () {
   if (fadeBool) {
      // ... unmodified content
   }
}