Unity-WaitForSeconds()不起作用 [英] Unity - WaitForSeconds() does not work

查看:470
本文介绍了Unity-WaitForSeconds()不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一些飞行模拟器程序.现在,我试图让该级别在4秒钟的延迟后重新启动,但是它一直在等待并且没有响应.这是我现在的代码(在C#中):

I am developing some flight simulator programme. Right now I am trying to get the level to restart after a delay of 4 seconds, but instead it is waiting forever and not responding. This is my code (in C#) right now:

void Update () {

    //other irrelevant code in front

    float TerrainHeightLocation = Terrain.activeTerrain.SampleHeight (transform.position);

    if (TerrainHeightLocation > transform.position.y) { //the plane crashed

        StartCoroutine(Wait(TerrainHeightLocation));


    }
}

IEnumerator Wait( float TerrainHeightLocation) {
    transform.position = new Vector3 (transform.position.x,
                                      TerrainHeightLocation,
                                      transform.position.z);
    Instantiate(explosion, transform.position, transform.rotation);
    Destroy(gameObject);

    Debug.Log ("Waiting");
    yield return new WaitForSeconds(4.0f); // waits x seconds

    Debug.Log ("Waited for x seconds");

    Application.LoadLevel(Application.loadedLevel);
    Debug.Log ("Reloaded level");

}

如果任何人都可以在代码中找到问题,那将是一个很大的帮助,因为我已经整天都在努力,而且无法修复.

It would be a great help if anyone could find a problem in the code, because I have been trying all day and I cannot fix it.

谢谢!

推荐答案

通常,当WaitForSeconds无法正常工作时,这是两件事之一:

Typically when WaitForSeconds doesn't work it's one of two things:

  1. Time.timeScale设置为0.
  2. 在时间到之前,该对象已被破坏或变为非活动状态.

在您的情况下,您要在调用yield WaitForSeconds之前销毁运行协程的游戏对象.销毁被推迟到帧的末尾,这样代码直到执行屈服时才执行,但是GameObject& MonoBehaviour将被销毁,协程也将被销毁.

In your case you are destroying the very game object that runs the Coroutine before you call yield WaitForSeconds. Destroy is deferred until the end of the frame so the code up until the yield will execute, but then the GameObject & MonoBehaviour will be destroyed and the Coroutine along with it.

解决方案:在关卡结束和重启之间持续存在的对象上使用协程.为了使对象即使在加载关卡时也仍然有效(就像在代码中一样),您需要调用

Solution: use a Coroutine on an object that persists between the level ending and restarting. To make an object persist even when a level is loaded (as you are doing in your code) you need to call DontDestroyOnLoad.

这篇关于Unity-WaitForSeconds()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆