2013-04-29 23 views
1

我有一個選手對象下面的代碼:產量waitforseconds()不工作

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"; 
} 

當爆炸功能所謂的鬆散函數被調用,並且我看到「yield之前」消息被打印出來。我等了三秒鐘,但我從來沒有看到「收益率」信息。

如果我拿出產量,這個函數按照我的預期減去等待3秒。

這是在Unity 4上。此代碼直接來自我相信是在Unity 3.5上創建的教程。我假設代碼在Unity 3.5中工作,因爲在網站上沒有評論爲什麼收益不起作用。

我做錯了什麼蠢事?

回答

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()); 
} 
+0

謝謝,這讓我足夠接近完成它。我在Destroy之前放置了yield StartCoroutine(GUI.Lose())。在此之前,我設置了renderer.enabled = false;所以我的遊戲對象會隱藏。 Lose()函數完成,然後我的gameObject被銷燬。 – 2013-04-29 14:22:57

+0

說明:因爲可以使用yield語句在任何點暫停協程的執行。 – Joetjah 2013-04-29 14:25:49

0

您也可以考慮在您失去功能使用簡單的調用。

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(); 
}