GamerC42
GamerC42

Reputation: 29

Fading into scenes in unity does not work correctly

When I fade out of a scene in unity and try to fade back into the original screen, I am met with a black screen. For example, going back to the main menu from the pause screen leaves me with a black screen and I believe it is a problem with my code. How should I fix this?

using UnityEngine;
using System.Collections;

public class Fading : MonoBehaviour 
{
    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.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()
    {
        alpha = 1;
        BeginFade(-1);
    } 
}

Upvotes: 1

Views: 294

Answers (2)

Hindrik Stegenga
Hindrik Stegenga

Reputation: 100

Brackeys has a simple and effective way to fade in and out between scenes: https://www.youtube.com/watch?v=0HwZQt94uHQ

Upvotes: 1

Adam
Adam

Reputation: 33146

Your code says:

  1. When game starts, immediately start fading.
  2. OnGUI (called anywhere from 30 to 100 times per second): fade out
  3. If you call the method BeginFade ... do nothing (you are already fading)
  4. Carry on fading to black forever.

There is never a piece of code to STOP fading.

You could add a bool "isFading" and put all the OnGUI code in:

if( isFading )
{
 ...
}

...but you'll still need to STOP at some point. e.g. the last line of OnGUI could be:

if( isFading && alpha <= 0 )
   isFading = false;

Upvotes: 2

Related Questions