问题描述
我让一个Singleton LevelManager加载一个关卡,等待新加载的关卡中的脚本将GameObject分配给LevelManager,然后对其进行处理.
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.
我有以下代码:
// 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;
}
问题在于,"yay"永远不会被打印出来.
The problem is that "yay" never gets printed.
我已经读过一些书,发现当携带协程的GameObject被销毁时,可能会发生这种情况.但是,LevelManager绝对不会在此过程中被破坏,所以我很茫然.
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.
推荐答案
问题是,您不是在LevelManager上而是在某些gameObject"上启动协程,很可能将其销毁,并且协程将停止执行.
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.
您可以通过将调用StartCoroutine移至新方法中来解决此问题,如下所示:
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
}
}
或直接调用LevelManager的StartCoroutine
or calling the StartCoroutine of LevelManager directly
void somefunction(sceneToLoad){
LevelManager.Instance.StartCoroutine(LevelManager.Instance.loadLevel(sceneToLoad));
}
这篇关于while循环后Unity3d协程停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!