IEnumerator在Unity中的使用
IEnumerator的原理
首先我们要明白,unity的代码是按照顺序进行执行的,然后在一些特定的函数中会进行一帧一帧的运行。假设我们需要修改一个函数的运行时间,让它延迟一段时间在运行,应该怎么操作呢?IEnumerator就可以起到这个作用,比如某个物体需要在0.5秒后做出变化,我们就可以将这个变化的函数设计为两秒后运行就可。在这个函数里添加:
yield return new WaitForSeconds(0.5f);
协程函数是通过StartCoroutine()函数进行调用的,StartCoroutine(方法,参数),只能通过StopAllCoroutines来结束;或者StartCoroutine(”字符串的方法名字”,参数),可以使用StopCoroutine(”字符串的方法名”)来结束协程。后方法只支持一个参数。
需要注意的是:
1.当某一个脚本中的协程在执行过程中,如果我们将该脚本的enable设置为false,协程不会停止。只有将挂载该脚本的物体设置为SetActive(false)时才会停止。
2.Unity在调用StartCoroutine()后不会等待协程中的内容返回,会立即执行后续代码。
特殊嵌套关系
下面展示一些 内联代码片
。
void Start () {
Debug.Log("start1");
StartCoroutine(Test());
Debug.Log("start2");
}
IEnumerator Test()
{
Debug.Log("test1");
yield return StartCoroutine(DoSomething());
Debug.Log("test2");
}
IEnumerator DoSomething()
{
Debug.Log("load 1");
yield return null;
Debug.Log("load 2");
}
运行结果是:
start1
test1
load1
start2
load2
test2
说明:这种StartCoroutine中嵌套一个yield return StartCoroutine,第一个StartCoroutine会等到第二个StartCoroutine中所有代码结束后再继续执行。
示例代码
下面展示一些 内联代码片
。
void Fade()
{
for (float f = 1f; f >= 0; f -= 0.1f)
{
Color c = renderer.material.color;
c.a = f;
renderer.material.color = c;
yield return null;//下一帧继续执行for循环
yield return new WaitForSeconds(0.1f);//0.1秒后继续执行for循环
}
}
参考:
https://blog.csdn.net/qq_15379219/article/details/80507864
https://www.cnblogs.com/fly-100/p/3910515.html