13.2.3 协程的延时执⾏原理
上⼀⼩节的例⼦展⽰了迭代器函数的使⽤⽅法,但是它是在1帧内直接运⾏完毕的,没有体现出“延时运⾏”的功能。下⾯对它做⼀些改动,引⼊定时功能。
using System.Collections.Generic;
using UnityEngine;
public class MyIter2 : MonoBehaviour
{
IEnumerator<int> HelloWorld()
{
transform.position = new Vector3(1, 0, 0);
yield return 1;
transform.position = new Vector3(2, 0, 0);
yield return 2;
transform.position = new Vector3(3, 0, 0);
yield return 1;
}
IEnumerator<int> e;
float helloTime = 0;
void Start()
{
e = HelloWorld();
}
void Update()
{
if (e != null)
{
if (Time.time > helloTime)
{
if (!e.MoveNext())
{
// 协程结束了
e = null;
return;
}
Debug.Log("yield返回值:"+e.Current);
// 把返回值当作延迟的时间
helloTime = Time.time + e.Current;
}
}
}
}
将这个脚本挂载到⽴⽅体上,运⾏游戏,可以展⽰出⽴⽅体间隔1~2秒改变⼀次位置的效果。注意这个脚本与第⼀个迭代器脚本最⼤的区别在于,e.MoveNext⽅法是在Update函数中执⾏的。Update函数每帧调⽤,不需要再使⽤循环。