1
votes

I'm using this code to fade in a CanvasGroup at the beginning of my scene loading, and then if the player loses I want to fade out the scene and reload it from the beginning.

void Update () {
    if (Time.time < 1 && fade.alpha >= 0)
        fade.alpha = .99f - Time.time;
    if (fadeOut)
        fade.alpha += .02f;
    if (fade.alpha >= 1)
    {
        Debug.Log("Change scene");
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}

The problem is that when it hits this it shows the gamescene twice in the hierarchy, and neither one on the screen. I'll upload a picture below. When it does this is also hits the Debug.Log repeatedly. enter image description here
Does this not work if it's the only scene in the project? Only thing I can think of.

I've updated the method to include a boolean to ensure it SHOULD only run one time. Somehow it is still running countless times until I end the unity editor. The new update method is this :

void Update () {
    if (Time.time < 1 && fade.alpha >= 0)
        fade.alpha = .99f - Time.time;
    if (fadeOut)
        fade.alpha += .02f;
    if (fade.alpha >= 1 && !reloadStarted)
    {
        Debug.Log("Change scene");
        reloadStarted = true;
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);

    }
}
2

2 Answers

1
votes

I guess Update is executed more rapidly than the scene is reloaded. So it starts to reload on every update. Introduce a bool property to indicate, that reload is already started.

if (fade.alpha >= 1 && !isReloadStarted)
{
    Debug.Log("Change scene");
    SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    isReloadStarted = true;
}

Furthermore according to your description, you might want to reload when fade.alpha is less or equal to 0.

fade.alpha <= 0
0
votes

I ended up refactoring the code and implementing this in a completely different way. I still don't know why it was acting so weird.