我在播放器对象中有以下代码:
function Start ()
{
GUI = GameObject.FindWithTag("GUI").GetComponent(InGameGUI);
}
function OnCollisionEnter(hitInfo : Collision)
{
if(hitInfo.relativeVelocity.magnitude >= 2) //if we hit it too hard, explode!
{
Explode();
}
}
function Explode() //Drop in a random explosion effect, and destroy ship
{
var randomNumber : int = Random.Range(0,shipExplosions.length);
Instantiate(shipExplosions[randomNumber], transform.position, transform.rotation);
Destroy(gameObject);
GUI.Lose();
}
我的GUI.Lose()函数如下所示:
function Lose()
{
print("before yield");
yield WaitForSeconds(3);
print("after yield");
Time.timeScale = 0;
guiMode = "Lose";
}
当调用explode函数时,调用松散函数,我看到“在yield之前”打印出消息。我等了三秒钟,但我从未看到“收获后”的消息。
如果我取出产量,该功能可以正常工作,减去等待3秒。
这是在Unity 4上。这段代码直接来自我认为是在Unity 3.5上创建的教程。我假设代码在Unity 3.5中有效,因为在网站上没有评论为什么收益率不起作用。
我做错了什么蠢事?
答案 0 :(得分:4)
您需要使用StartCoroutine,如下所示:
function Explode() //Drop in a random explosion effect, and destroy ship
{
var randomNumber : int = Random.Range(0,shipExplosions.length);
Instantiate(shipExplosions[randomNumber], transform.position, transform.rotation);
Destroy(gameObject);
// Change here.
yield StartCoroutine(GUI.Lose());
// Or use w/out a 'yield' to return immediately.
//StartCoroutine(GUI.Lose());
}
答案 1 :(得分:0)
您也可以考虑在丢失函数上使用简单的Invoke。
function Start ()
{
GUI = GameObject.FindWithTag("GUI").GetComponent(InGameGUI);
}
function OnCollisionEnter(hitInfo : Collision)
{
if(hitInfo.relativeVelocity.magnitude >= 2) //if we hit it too hard, explode!
{
Explode();
}
}
function Explode() //Drop in a random explosion effect, and destroy ship
{
var randomNumber : int = Random.Range(0,shipExplosions.length);
Instantiate(shipExplosions[randomNumber], transform.position, transform.rotation);
Destroy(gameObject);
Invoke("YouLose", 3.0f);
}
function YouLose()
{
GUI.Lose();
}