0
\$\begingroup\$

Here's my code:

IEnumerator SceneIsInChange(AsyncOperation SecondScene)
    {
        Snake.SetActive(true);
        print("1: " + FinalLoop);
        while (!SecondScene.isDone)
        {
            yield return null;
        }
        Snake.GetComponent<Animator>().SetBool("Loaded", true);
        print("2: " + FinalLoop);
        while (!FinalLoop)
        {
            yield return null;
        }
        print("3: " + FinalLoop);
        Time.timeScale = 1;
        Loading = false;
        LoadingScene = null;
    }

The problem is that the coroutine gets suspended before print("2: " + FinalLoop); line. (But print("1: " + FinalLoop works) So the problem should be in the first while loop but I can't find it. There's only one single code in that loop but it's supposed to "wait for one frame before resuming coroutine" so it shouldn't stop the coroutine.

Am I wrong about yield return null; meaning or the problem is somewhere else?

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

Coroutines are stopped when their corresponding game object is deactivated or destroyed, regarding your code logic, it's possible after the scene change, the game object in previous scene as well as Its coroutine are destroyed

Your assumption about yield return null is also true

\$\endgroup\$
4
  • \$\begingroup\$ I don't get it. According to what I've seen in tutorials, the scene won't change until the coroutine is finished, isn't that correct? \$\endgroup\$
    – Arian_ki
    Commented Feb 24, 2022 at 21:51
  • 2
    \$\begingroup\$ Scene loading is not dependent on any coroutine by default unless you set "allowSceneActivation" property of the operation to false from the beginning and set to true in the end of coroutine \$\endgroup\$
    – Hesamom
    Commented Feb 24, 2022 at 21:58
  • \$\begingroup\$ Hey, thanks! I didn't know about that property \$\endgroup\$
    – Arian_ki
    Commented Feb 24, 2022 at 22:02
  • \$\begingroup\$ You're welcome, please mark my answer as accepted \$\endgroup\$
    – Hesamom
    Commented Feb 25, 2022 at 19:45
1
\$\begingroup\$

Thanks to @Hesamom I found a solution:

All you need to do is to add AsyncOperation.allowSceneActivation = false so it won't activate itself right after loading, and then change it to true once you did all you wanted (usually at the last line of coroutine)

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .