Unity3d coroutine stops after while-loop

2019-07-14 06:14发布

问题:

I have a singleton LevelManager loading a level, waiting for a script from the newly-loaded level to assign a GameObject to the LevelManager to then do stuff with it.

I have the following code:

// some GameObject calls the loadLevel coroutine
void somefunction(sceneToLoad){
    StartCoroutine(LevelManager.Instance.loadLevel (sceneToLoad));
}

// snippet of LevelManager.cs
public GameObject levelPrepper = null;
public IEnumerator loadLevel(string levelName){
    Application.LoadLevel (levelName);
    while (!levelPrepper)
        yield return null;
    yield return StartCoroutine (waitForLevelPrepper());
    print("yay");
    //do stuff
}

//snippet of the levelPrep.cs:
void Awake(){
    LevelManager.Instance.levelPrepper = gameobject;
}

The problem is that "yay" never gets printed.

I've done some reading and found that this might happen when the GameObject carrying the coroutine is destroyed. However, LevelManager is definitely never destroyed during the process, so I'm at a loss.

回答1:

The issue is that you start the Coroutine not on the LevelManager, but on "some gameObject", that most likely will be destroyed and its coroutine will stop being executed.

You could fix that by moving the call StartCoroutine into a new method, like this :

void somefunction(sceneToLoad)
{
    LevelManager.Instance.LoadLevel(sceneToLoad));
}


public class LevelManager
{
    public void LoadLevel(string levelName)
    {
        StartCoroutine(LoadLevelCoroutine);
    }

    private GameObject levelPrepper = null;
    private IEnumerator LoadLevelCoroutine(string levelName){
        Application.LoadLevel (levelName);
        while (!levelPrepper)
            yield return null;
        yield return StartCoroutine (waitForLevelPrepper());
        print("yay");
        //do stuff
    }
}

or calling the StartCoroutine of LevelManager directly

void somefunction(sceneToLoad){
    LevelManager.Instance.StartCoroutine(LevelManager.Instance.loadLevel(sceneToLoad));
}