可以把yield了解成一種特殊形式的return,它和return一樣,會立即把執行權傳回父級函數。特别之處在于,yield後面跟的函數或對象會跟一個條件判斷,當條件滿足時,就會再次回調包含該yield的子函數,并且從yield語句之後繼續執行。條件滿足之前,執行父函數下面的語句,可以看作異步執行。
例如:
js:
callYieldFunction();
Debug.Log("print second");
function callYieldFunction()
{
Debug.Log("print first");
yield new WaitForSeconds(2);
Debug.Log("print after 2 seconds");
}
c#:
//在c#中必須顯示的指明,啟動一個線程以調用含有yield的函數。
StartCoroutine(callYieldFunction());
Debug.Log("print second");
//在c#中含有yield的函數,傳回值必須為IEnumerator
IEnumerator callYieldFunction()
{
Debug.Log("print first");
yield return new WaitForSeconds(2);
Debug.Log("print after 2 seconds");
}
當沒有父函數可以傳回,本身已經是頂級函數的時候,yield的條件相當于同步執行,程式一直等到條件滿足,才繼續執行下面的語句。
例如:
js: function Start()
{
Debug.Log("print first");
yield new WaitForSeconds(2);
Debug.Log("print after 2 seconds");
}
c#:IEnumerator Start() //注意c#中的傳回值
{
Debug.Log("print first");
yield return new WaitForSeconds(2);
Debug.Log("print after 2 seconds");
}
在了解了這個之後,就可以了解使用嵌套的yield,來實作同步的子線程調用。
例如:因為start函數已經是頂級函數,是以外層的yield會”死在這裡“,直到嵌套的線程執行完畢,再繼續執行。
js: function start()
{
yield StartCoroutine("callYieldFunction");
Debug.Log("print latest");
}
function callYieldFunction()
{
Debug.Log("print first");
yield new WaitForSeconds(2);
Debug.Log("print after 2 seconds");
}
c#:
IEnumerator Start()
{
yield return StartCoroutine("callYieldFunction");
Debug.Log("print latest");
}
IEnumerator callYieldFunction()
{
Debug.Log("print first");
yield return new WaitForSeconds(2);
Debug.Log("print after 2 seconds");
}