I am using the following code to fade from one scene to another, but it doesn't fade. It just loads the next scene without fading. I suspect there's something wrong with the image I'm using. I used a black .png image with dimensions 425×344 that I downloaded from Google. How can I solve this issue?

Fading.cs (I added this to an empty game object)

public Texture2D fadeOutTexture;
public float fadeSpeed = 0.8f; 

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

void onGUI () {

    alpha += fadeDir * fadeSpeed * Time.deltaTime;
    alpha = Mathf.Clamp01(alpha);
    GUI.color = new Color (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() {
    BeginFade (-1);


In the script of the trigger object:

IEnumerator gameScene2() {
    float fadeTime = GameObject.Find ("FadeObject").GetComponent<Fading>().BeginFade(1);
    yield return new WaitForSeconds(fadeTime);

These are the image settings for the black .png image

enter image description here


1 Answer 1


Some things I noticed:

  • onGUI and onLevelWasLoaded should be OnGUI/OnLevelWasLoaded
  • You forgot to set the red component here, so you are not setting the alpha value of the color

    GUI.color = new Color (GUI.color.g, GUI.color.b, alpha);

  • Try to set the alphaBlend parameter to true on the DrawTexture function (I think it's true by default, but I didn't test it, so give it a try):

    GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), fadeOutTexture, ScaleMode.StretchToFill, true);

  • You shouldn't change the alpha value in the OnGUI function, it's better to do in the Update

  • I don't know how you are using the code, but remember that Unity will destroy the object you attached the script on when you load a new scene. I suggest you to write a static class to switch levels, or use DontDestroyOnLoad on your GameObject

  • \$\begingroup\$ Note: the reason to do change the alpha in Update rather than OnGUI is that OnGUI is called multiple times per frame, so your fade would go faster than you would otherwise predict. \$\endgroup\$
    – Ed Marty
    Sep 10, 2017 at 3:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .