Coroutine causes Unity to freeze

Hello guys!

I have been trying to get this coroutine to work correctly:

public void TriggerLoading(int loadTimeInSeconds) {

        StartCoroutine(Load(loadTimeInSeconds));

    }

    IEnumerator Load(int Seconds) {

        isLoading = true;

        _loadingBackground.SetActive(true);
        _loadingText.gameObject.SetActive(true);
        _loadingText.text = "Loading";

        yield return null;
        yield return new WaitForSeconds(Seconds);

        _loadingBackground.SetActive(false);
        _loadingText.gameObject.SetActive(false);

        isLoading = false;
       
    }

But every time I hit play, my Load coroutine freezes Unity.
I have no loops in it that would cause an infinite loop, so I am not sure why Unity freezes up when trying to execute the coroutine.

Are you setting time scale? WaitForSeconds uses scaled time so if you set it to 0 them it will never exit.

1 Like

If that is the case, you can iterate and add Time.unscaledDeltaTime to a variable and yield return null until that variable gets larger than your desired wait time.

To wait 1.23 seconds with unscaled time:

        for( float t = 0; t <= 1.23f; t += Time.unscaledDeltaTime)
        {
            yield return null;
        }

The other thing to look at is if any scripts on the objects referred to in lines 11 and 12 above contain code that calls TriggerLoading() on Awake() or OnEnable(), you are going to be in an infinite loop without even meaning to.

To test this latter theory, put a yield return null at the very start of your coroutine, which will “break” that cycle of endless loading, causing Unity to not freeze, but obviously you still have the logic problem to solve on your own.

1 Like

You could also use waitForSecondsRealtime :wink:

2 Likes

Touche. Heh. TIL!

Also though, since he is seeing a LOCK, I think it isn’t so much that his Timescale is zero.

1 Like

Ah, found the problem.
Turns out the Coroutine was not the problem, but a loop else where that was watching the IsLoading variable, and waiting for it to change to false. :sweat_smile:

Thank you Karl and Kurt for your vigorous responses! :slight_smile:
I had not known that WaitForSeconds relied on TimeScale, and at first, I had thought that might be the issue, since I did have a Pause function that did set the time scale to zero. This checked out though, as I was not pausing the game before calling upon the Coroutine.
Thanks again guys. :smile:

2 Likes

Wait, when did you sneak that one in?

And thanks.

1 Like