测试1:
using UnityEngine;
using System.Collections; public class test1 : MonoBehaviour { // Use this for initialization
void Start ()
{
Debug.Log("in start " + Time.time.ToString());
StartCoroutine(callYieldFunction()); //必须要用StartCoroutine
Debug.Log("in start 2 " + Time.time.ToString());
} // Update is called once per frame
void Update () { } IEnumerator callYieldFunction()
{
Debug.Log("callYieldFunction " + Time.time.ToString());
//yield return StartCoroutine(callYieldFunction1());
StartCoroutine(callYieldFunction1());
yield return new WaitForSeconds();
Debug.Log("callYieldFunction print after 2 seconds " + Time.time.ToString());
} IEnumerator callYieldFunction1()
{
Debug.Log("callYieldFunction1 " + Time.time.ToString());
yield return new WaitForSeconds();
Debug.Log("callYieldFunction print after 4 seconds " + Time.time.ToString());
}
}
运行结果为
in start 0
callYieldFunction 0
callYieldFunction1 0
in start 2 0
callYieldFunction print after 4 seconds 2.004971
callYieldFunction print after 2 seconds 2.004971
测试2:
using UnityEngine;
using System.Collections; public class test1 : MonoBehaviour { // Use this for initialization
void Start ()
{
Debug.Log("in start " + Time.time.ToString());
StartCoroutine(callYieldFunction()); //必须要用StartCoroutine
Debug.Log("in start 2 " + Time.time.ToString());
} // Update is called once per frame
void Update () { } IEnumerator callYieldFunction()
{
Debug.Log("callYieldFunction " + Time.time.ToString());
yield return StartCoroutine(callYieldFunction1());
//StartCoroutine(callYieldFunction1());
yield return new WaitForSeconds();
Debug.Log("callYieldFunction print after 2 seconds " + Time.time.ToString());
} IEnumerator callYieldFunction1()
{
Debug.Log("callYieldFunction1 " + Time.time.ToString());
yield return new WaitForSeconds();
Debug.Log("callYieldFunction print after 4 seconds " + Time.time.ToString());
}
}
运行结果为:
in start 0
callYieldFunction 0
callYieldFunction1 0
in start 2 0
callYieldFunction print after 4 seconds 2.002947
callYieldFunction print after 2 seconds 4.007511
结果:
需要注意的是StartCoroutine(callYieldFunction());这句必须要加StartCoroutine,不然callYieldFunction()里面根本不会运行。
1:StartCoroutine里面的函数是个闭包,主线程运行这个闭包,直到yield return,闭包中剩下的代码不运行,跳出闭包,运行主线程别的代码;
2:主线程在下一帧运行yield return后面的函数(估计是把所有闭包放在一个list里面,每帧的一个特点时间执行list里面的闭包)。
3:整个闭包应该保存了堆栈信息