触发器激活后如何等待5秒钟?

时间:2015-02-09 07:31:11

标签: c# triggers unity3d

我试图在触发器满足后等待五秒钟,然后在五秒钟后我想要进入下一个场景。问题是一旦触发得到满足,它就会自动进入下一个场景。

我尝试了什么

using UnityEngine;
using System.Collections;

public class DestroyerScript : MonoBehaviour {


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

}
void Update()
{

        StartCoroutine(WaitAndDie());         

}
void OnTriggerEnter2D(Collider2D other)
{
    if (other.tag == "Player") 
    {
        Update();     
        Application.LoadLevel("GameOverScene");
        return;
    }

}
}

我也尝试了

using UnityEngine;
using System.Collections;

public class DestroyerScript : MonoBehaviour {


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

}

void OnTriggerEnter2D(Collider2D other)
{
    if (other.tag == "Player") 
    {
        StartCoroutine(WaitAndDie());         
        Application.LoadLevel("GameOverScene");
        return;
    }

}
}

2 个答案:

答案 0 :(得分:5)

仅在Application.LoadLevel之后调用yield return。)。

IEnumerator WaitAndDie()
{
    yield return new WaitForSeconds(5);
    Application.LoadLevel("GameOverScene");
}

void OnTriggerEnter2D(Collider2D other)
{
    if (other.tag == "Player") 
    {
        StartCoroutine(WaitAndDie());         
        return;
    }

}
}

答案 1 :(得分:2)

这应该有效

using UnityEngine;
using System.Collections;

public class DestroyerScript : MonoBehaviour {


bool dead;

IEnumerator OnTriggerEnter2D(Collider2D other)
{
    if (other.tag == "Player") 
    {
        yield return new WaitForSeconds(5);
        Application.LoadLevel("GameOverScene");
        dead = true;
        return dead;

    }

}
}