Coroutine [somtimes] stopps working

Hey there !

Im currently trying to make a smooth fadeout of a canvas group. So i have this class here as an helper :

public class UIgroup {

    public static float time = 1f;


    public static IEnumerator canvasFadeIn(CanvasGroup canvasGroup)
    {

        while (canvasGroup.alpha <= 1)
        {
            canvasGroup.alpha += Time.deltaTime / time;
            yield return null;


        }


    }


    public static IEnumerator canvasFadeOut(CanvasGroup canvasGroup)
    {
        //if(canvasGroup.alpha >= 0)

        while (canvasGroup.alpha >= 0)
        {
            canvasGroup.alpha -= Time.deltaTime / time;
            yield return null;


        }


    }


    public static void resetScene() {

        SceneManager.LoadScene("Illud");

    }



    }


    public class StartTextButton : MonoBehaviour, ButtonInterface {


    public CanvasGroup startScreenCanvasGroup;

    public CanvasGroup gameScreenCanvasGroup;


    public void onTouchUp()
    {

        StopAllCoroutines();

        StartCoroutine(UIgroup.canvasFadeOut(startScreenCanvasGroup));

        StartCoroutine(UIgroup.canvasFadeIn(gameScreenCanvasGroup));

        Camera.main.GetComponent<Main>().startTextWasClicked = true;

        Debug.Log("Clicked");

 

     }

    }

When i click for example on the start button, i call fadeOut like above in the OnClick method.

But sometimes suddenly the coroutine stopps working and the screen stays at about 0.5 alpha, or sometimes even 0.9 alpha. But that only happens sometimes, mostly its working. But when not its annoying and looks very strange. Does anyone have an idea, why this happens ? Thats by the way nearly all of my code. I have some more code that manages the canvas group interactable and block raycasting variables. But thats all.

Thanks for your help !

Are you getting any exceptions?

Coroutines are attached to whichever component calls them, and if you delete or disable that component, they stop. In your case, they’re attached to the StartTextButton button, so I’d guess something else is deleting or disabling that button during the screen fade.

1 Like

@Kurt-Dekker Nope, there are no exceptions :confused:
@makeshiftwings the Problem is, that i dont disable/delete the button. I just set the canvasGroup.interactable = false; later. But thats all, the Button stays active all the time …

PUSH

PUSH

Is onTouchUp getting called extra times? Do you get extra “Clicked” log lines? (i.e. check the log)

Try disable the load scene entirely and see if the fading finishes fully, so you get some intel about what might be interrupting it

how are you ensuring that the scene load is not called until the coroutines are done? I don’t see that in the above codelets.

I might suggest switching to a tweening engine as you can easily set up the fade and add calls to happen when the tween finishes, especially if you are having trouble rolling your own fade system.

1 Like