Error with Fader during Scene Transitions

I successfully used a fader in a practice game I made a few months back. I am now trying to implement a similar approach for my mobile game.

My goal: when a user goes to the play screen, the screen fades out, loads the scene async, and fades back in once that method is finished.

MY CODE

These are my variables:

CanvasGroup canvasGroup;
Coroutine currentActiveFade = null;
int sceneIndexToLoad = -1;
float fadeInTime = 2f;
float fadeOutTime =  1f;
float fadeWaitTime =  0.5f;

These are my secondary methods:

public void FadeOutImmediately()
    {
        canvasGroup.alpha = 1;
    }

    public Coroutine FadeOut(float time)
    {
        return Fade(1, time);
    }

    public Coroutine Fade(float target, float time)
    {
        if (currentActiveFade != null)
        {
            StopCoroutine(currentActiveFade);
        }
        currentActiveFade = StartCoroutine(FadeRoutine(target, time));
        return currentActiveFade;
    }
    
    private IEnumerator FadeRoutine(float target, float time)
    {
        while (!Mathf.Approximately(canvasGroup.alpha, target))
        {
            canvasGroup.alpha = Mathf.MoveTowards(canvasGroup.alpha, target, Time.deltaTime / time);
            yield return null;
        }
    }

    public Coroutine FadeIn(float time)
    {
        return Fade(0, time);
    }

This is my primary function, where I get my error:

public IEnumerator TransitionToNewScene()
    {
        if(sceneIndexToLoad < 0)
        {
            Debug.LogError("Scene to load is not set");
            yield break;
        }

        DontDestroyOnLoad(gameObject);

        //GETS STUCK ON THIS LINE
        yield return FadeOut(fadeOutTime);

        yield return SceneManager.LoadSceneAsync(sceneIndexToLoad); //this still executes

        yield return new WaitForSeconds(fadeWaitTime);
        FadeIn(fadeInTime);

        Destroy(gameObject);
    }

My code reaches and starts the FadeOut coroutine, and also loads the next scene. When I put a debug statement underneath my FadeOut call, it doesn't reach it, but seems to reach the next yield return.

MY ISSUE: The canvasGroup alpha reaches 1 in the next scene, but that's where it stops. The FadeIn code is not reached, and my gameObject is not destroyed. Why is this happening?

Please note: this code is almost exactly like in my previous project, which works perfectly.


Solution 1:

Don't do this Destroy(gameObject); until the fadein finishes, all coroutines will stop when gameobject is destroyed.

I might put it in the end of FadeRoutine:

private IEnumerator FadeRoutine(float target, float time)
{
    while (!Mathf.Approximately(canvasGroup.alpha, target))
    {
        canvasGroup.alpha = Mathf.MoveTowards(canvasGroup.alpha, target, Time.deltaTime / time);
        yield return null;
    }

    if(target == 0)
        Destroy(gameObject);
}