先解释下协同函数:一种可以中途停止执行等待某种条件吻合再继续执行的函数。
一般如下:
-
function TestCoroutines()
-
{
-
doSomething();
-
yield;
-
doOtherthing();
- }
测试代码:
-
function test()
-
{
-
Debug.Log("2nd step");
-
yield WaitForSeconds(2);
-
Debug.Log("4th step");
-
}
-
-
void Start()
-
{
-
Debug.Log("1st step");
-
yield;
-
test();
- Debug.Log("3rd step");
- }
- 0.00:1st step
- 0.10:2nd step
- 0.10:3rd step
-
2.10:4th step
yield可以什么都不带,也可以返回另一个协同函数,或者一个WaitForSeconds函数,各表示不同的延时:
什么都不带:延时一帧
带另一个协同函数:延时到另一个协同函数完全执行完毕
带WaitForSeconds:延时对应秒数。
还是上面的例子,稍微改变下:
-
function test()
-
{
-
Debug.Log("2nd step");
-
yield WaitForSeconds(2);
-
Debug.Log("4th step");
-
}
-
-
void Start()
-
{
-
Debug.Log("1st step");
-
yield test(); //这是改变的地方
- Debug.Log("3rd step");
- }
- 0.00:1st step
- 0.00:2nd step
- 2.00:4th step
-
2.00:3rd step