我尝试创建一个简单的启动画面。起初这个等待工作,但几个星期后突然这个代码不想工作。我尝试使用debug.log但是我在等待之前得到了#34;"等待"等待"即使在5分钟后也不会出现。我正在使用团结4.5,为什么会这样?
void Start () {
guiTexture.pixelInset = new Rect (0, 0, Screen.width, Screen.height);
StartCoroutine (LoadNextScene ());
}
IEnumerator LoadNextScene(){
Debug.Log ("before wait");
yield return new WaitForSeconds (DelayTime);
Debug.Log ("after wait");
if (NextLevel != "") {
Application .LoadLevel (NextLevel );
}
}
答案 0 :(得分:1)
仅是巩固@peterept给出的答案,以下可能是您的协程卡在WaitForSeconds
上的原因:
WaitForSeconds
中给定的时间太长。虽然这是愚蠢的原因,但有时会发生这种情况调用协程的对象已被破坏。您可以按照以下步骤进行检查。
void OnDestroy() {
Debug.Log("Destroyed");
}
StopAllCoroutines()
都被呼叫,这将停止您的协程。Time.timeScale
设置为0。因为当其为零时,它将阻止Time.deltaTime
增大,结果WaitForSeconds
永远不会达到您指定的值。您可以在Edit -> Project settings -> Time
中检查您当前的时间刻度,在其中检查“时间刻度”参数。或者,您可以在调用协程之前通过记录日志来检查其值。最后一个,我也遇到了,@ peterept的评论帮助了我。
答案 1 :(得分:0)
您的代码非常完美。这意味着两件事之一:
试试这个:
void Start () {
guiTexture.pixelInset = new Rect (0, 0, Screen.width, Screen.height);
StartCoroutine (LoadNextScene ());
}
IEnumerator LoadNextScene(){
Debug.Log ("before wait. Pausing for seconds: " + DelayTime);
yield return new WaitForSeconds (DelayTime);
Debug.Log ("after wait");
if (NextLevel != "") {
Application .LoadLevel (NextLevel );
}
}
void OnDestroy() {
Debug.Log("Destroyed");
}
答案 2 :(得分:0)
如果你真的需要等待几秒钟。您可以使用Invoke而不是Co例程。
到现在为止,我仍然无法理解为什么有人会在简单的基础上使用Co例程。
常规程序通常用于让它在后台执行自己的工作,而其他程序仍在运行。
Ex:检查游戏的在线数据。等等。下载资产。
这是使用Co例程的最佳方式。
但请注意,当你只想延迟一些Call时,只需使用Invoke。
void Start(){
Invoke("LoadMyScene",2);
// LoadMyScene will be called after 2 seconds.
}
public void LoadMyScene(){
Application.LoadLevel(YourLevelScenehere);
}
<强>更新强>