Waitforseconds没有等待

时间:2014-08-26 10:24:27

标签: c# unity3d

我有这个代码,当你完成游戏关卡时会加载。它应该冻结时间,缩放完成级别的消息,等待5秒然后加载下一级别并解冻时间。问题是WaitForSeconds不起作用。它只是加载下一级别而无需等待。我究竟做错了什么?

IEnumerator WaitingFunction(){
    yield return new WaitForSeconds(5);
}

void OnTriggerEnter ( Collider col )
{
    if (col.tag == "Player")
    {
        Time.timeScale = 0f;
        lvlcomplete.transform.localScale = new Vector3 (1,1,1);

        StartCoroutine(WaitingFunction());

        Time.timeScale = 1f;
        lvlcomplete.transform.localScale = new Vector3 (0,0,0);
        Application.LoadLevel(Application.loadedLevel+1);
        player.transform.position = new Vector3(0f, 0.3519309f, -2.381933f);
    }

3 个答案:

答案 0 :(得分:2)

当OnTriggerEnter代码继续立即加载关卡时,你启动一个等待5秒钟而不做任何事情的协程。

您应该在协程内部等待时间过后运行应该运行的代码:

IEnumerator WaitingFunction(){
    yield return new WaitForSeconds(5);

    Time.timeScale = 1f;
    lvlcomplete.transform.localScale = new Vector3 (0,0,0);
    Application.LoadLevel(Application.loadedLevel+1);
    player.transform.position = new Vector3(0f, 0.3519309f, -2.381933f);
}

答案 1 :(得分:1)

像LearnCocos2D一样,你必须移动代码。进一步使用timeScale = 0,您只需要等待相应的帧数:

IEnumerator WaitingFunction(){
    int noOfFramesToWait = (int)(seconds * Application.targetFrameRate);
    for (int i = 0; i < noOfFramesToWait; i++) {
        yield return null;
    }
    Time.timeScale = 1f;
    // do my stuff
}

如果您有几种情况,例如暂停,添加级别加载,游戏结束,淡入淡出,......下一步可以让这更通用:

void OnTriggerEnter ( Collider col ) {
    if (col.tag == "Player") {
        Time.timeScale = 0f;
        StartCoroutine (WaitForNFrames (5f, LoadNewLevel));
    }
}

public void LoadNewLevel () {
    Time.timeScale = 1f;
    // do my stuff
}

IEnumerator WaitForNFrames (float seconds, System.Action executeWhenFinished) {
    int noOfFramesToWait = (int)(seconds * Application.targetFrameRate);
    for (int i = 0; i < noOfFramesToWait; i++) {
        yield return null;
    }
    executeWhenFinished ();
}

另一件小事,也许你已经有了这个:你在调用LoadLevel之后引用了播放器对象。使用DontDestroyOnLoad加载新级别时,确保不会销毁它。

答案 2 :(得分:-2)

尝试重构您的代码,如下所示

WaitingFunction(){
    yield WaitForSeconds (5);
}

void OnTriggerEnter ( Collider col )
{
    if (col.tag == "Player")
    {
        Time.timeScale = 0f;
        lvlcomplete.transform.localScale = new Vector3 (1,1,1);

        StartCoroutine(WaitingFunction());

        Time.timeScale = 1f;
        lvlcomplete.transform.localScale = new Vector3 (0,0,0);
        Application.LoadLevel(Application.loadedLevel+1);
        player.transform.position = new Vector3(0f, 0.3519309f, -2.381933f);

                }