How to Fade a screen in Unity?

Hi I have this following code as suggested on this link:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class ScreenFader : MonoBehaviour
{
    public Texture2D fadeOutTexture;

    public float fadeSpeed = 0.8f;
    public float minAlpha = 0.0f;
    public float maxAlpha = 1.0f;
    public int drawDepth = -1000;

    private float alpha = 1.0f;
    private int fadeDir = -1;

    void OnGUI()
    {
        alpha += fadeDir * fadeSpeed * Time.deltaTime;
        alpha = Mathf.Clamp01 (alpha);
        alpha = Mathf.Clamp(alpha, minAlpha, maxAlpha);

        GUI.color = new Color (GUI.color.r, GUI.color.g, GUI.color.b, alpha);
        GUI.depth = drawDepth;
        GUI.DrawTexture (new Rect (0, 0, Screen.width, Screen.height), fadeOutTexture);
    }

    public float BeginFade(int direction)
    {
        fadeDir = direction;
        return fadeSpeed;
    }

    void OnLevelWasLoaded(int level)
    {
        BeginFade (-1);
    }
}

This works nice on the game I am working on. I literally wasted like entire work day on this one. I am so astound that Unity doesn’t have a fade screen built in that it has to provided on the asset store! Why is this so? Not even a health bar built in. It seems there are majority of games out there that didn’t have fade and health bars in them. So maybe there’s that.

There is a problem on the script. I have a particular GUI element that I use that must be on top of this fade. Unfortunately, this will fade the entire screen including all the UI elements. This is not what I need, I want to apply the fade on the entire game and just leave some elements unfaded. It seems that GUI.depth is applied entirely on the GUI system. This is not explained on the video, I believe.

I also wanted to add blur effect such that all the things in the background is blurred and then partially faded. But this is entirely a different question begging for a new thread but just in case you wondering what I am trying to do. How am I to go forward about this?

Try using a canvas and the ui. You’ll have more control, and it’ll be a lot simpler than ongui.

For blurring the screen, you’ll want to use a render texture to capture the screen, overlay it (canvas + raw image works nicely for this). The trick though is you’ll need a blur shader for the texture. If I recall there is one on the wiki.

1 Like

Suppose you currently have level 1 loaded and displayed. You want a 10 second fade out to black before you load level 2. (Ignore the fade in for now)

Do you recommend using a fade method that has a callback to ‘load level 2’ when it’s done? Because I really hate game loop functions in update that poll some variable on every frame just looking for that 0.0001% chance a variable becomes true.