using UnityEngine;
using System.Collections;
public class CoroutineExample : MonoBehaviour
{
IEnumerator Start()
{
print ("Starting " + Time.time);
yield return StartCoroutine (WaitAndPrint());
print ("Done " + Time.time);
}
IEnumerator WaitAndPrint()
{
yield return new WaitForSeconds (5f);
print ("WaitAndPrint " + Time.time);
}
}
Starting 0
WaitAndPrint 5.010554
Done 5.010554
我有兩個問題嗎?
首先,如何理解函數Start()的返回值。我曾經看到Start()的返回值是void。在我看來,Start()只能通過Unity執行一次(一幀),但是yield返回似乎使Start()函數在兩幀中執行;
其次,我也對結果感到困惑。我認爲結果應該是
Starting 0
Done 5.010554
WaitAndPrint 5.010554
由於StartCoroutine()啓動函數WaitAndPrint()。在函數WaitAndPrint()中,收益率返回使此函數在此幀中暫停並返回到Start()。然後開始()繼續並打印「完成xxxxx」。 5秒鐘後,WaitAndPrint()恢復並打印「WaitAndPrint xxxxx」。
我在哪裏錯了?
基於對象的類型和對象的值Unity將決定做什麼。 這就是要點! – mingchaoyan