Hugo Fouquet
Hugo Fouquet

Reputation: 149

LoadScene with Fading C#

I use Unity 5.3.1. I want change Scene with a fade effect.

Everything is working, but, my new scene "grayed" ... Like this :

grayed image enter image description here

Instead of :

regular image enter image description here

My fading :

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)
{
    Debug.Log("BeginFade");
    fadeDir = direction;
    return fadeSpeed;
}

void OnLevelWasLoaded(int level)
{
    Debug.Log("wasLoaded");
    BeginFade(-1);
}

}

And Mycode who performs my scene :

 IEnumerator ChangeLevel()
{
    float fadeTime = GameObject.Find("GM").GetComponent<Fading>().BeginFade(1);
    yield return new WaitForSeconds(fadeTime);
    SceneManager.LoadScene(scene);
}

And the call of my ChangeLevel function :

 if (other.gameObject.name == "MenuController")
 {
    StartCoroutine(ChangeLevel());
 }

Upvotes: 1

Views: 1388

Answers (2)

Mike Xiao
Mike Xiao

Reputation: 51

I think this is because of the lighting bug in Unity 5. It happens a lot when the game level is reloaded.

Go to Unity>Window>Lighting, uncheck the auto option at the bottom in dialog, then test your game again.

Here's the instruction: How to disable auto light baking in Unity

Upvotes: 1

Entwicklerpages
Entwicklerpages

Reputation: 126

Is your GameObject set as DontDestroyOnLoad? Also I think you have a logical mistake in your code. You call WaitForSeconds with the time delivered by BeginFade. That time is fadeSpeed wich is not the same as the time you wait before the screen is black. At the moment your alpha += fadeDir * fadeSpeed * Time.deltaTime; says that every second, add a value of 0.8 to alpha. But Alpha is only completly transparent if it is set to one.

So the actual time should be 1 / fadeSpeed, I think (1.25s). Why the screen remains gray I cannot tell you. It should go down unless it is 0.

Now, it is not a good idea to have a component with OnGUI enabled the whole time. Even if it doesn't show something, the fact that your MonoBehavior have a OnGUI method creates a big overhead. Since Unity5 released there are many better way's to do screenfading. Just Google a little bit and you find project's like theese (not tested):

Upvotes: 0

Related Questions