using System.Collections;//IEnumerator在System.Collectins包下
using System.Collections.Generic;
using UnityEngine;//为了用UnityEngine下的MonoBehaviour和Time
using UnityEngine.UI;//为了用UnityEngine.UI下的Text
public class test : MonoBehaviour
{
public Text MyText;
public Text count1Text;
public int count1 = 0;
public int count2 = 0;
// Start is called before the first frame update
void Start()
{
StartCoroutine(Out());
count1 += 1;
count1Text.text = "count1:" + count1;
}
IEnumerator Out()
{
for(int i=0;i<1000;i++)
{
count2 += 1;
MyText.text = "Count2:" + count2;
yield return new WaitForSeconds(0.3f);//等待0.3秒继续执行。
}
}
}
运行结果:开启协程out()后,out()等待0.3秒后继续执行out(),这个协程不影响主线程的运行,还没有运行完成out()就已经在执行StartCoroutine()在之后的代码了。
协程的作用:在我看来,游戏中有许多过程(Process)需要花费多个帧和时间去计算,为了让游戏流畅,不让游戏一直等待这个过程的执行完成。我们开启一个协程来把工程分在几个帧里完成,主线可以有时间继续完成需执行的任务,当然协程也是在主线程中执行。
调用协程:
- StartCoroutine(Out()),即 StartCoroutine(方法),这个方法可以给调用的方法传很多个参数,只能通过StopAllCoroutines来结束协程,StartCoroutine调用的方法的返回值必须是IEnumerator。
- StartCoroutine(“Out”),即 StartCoroutine(“方法名”),这个方法可以给调用的方法最多传一个个参数,可以通过StopCoroutines来结束协程。
yield return Expression的作用是将控制权还给外部并保存当前代码的位置,unity3d每帧都会调用IEnumerator中的MoveNext()方法判断Expression是否为满足,如果满足,就会从yield return Expression下一条语句开始运行。
快速实现迭代器: 返回IEnumerator , 使用yield关键字。
IEnumerator 方法名称()
{
yield return 值;
}
使用yield return x(x是指一个具体的对象或数值)的话,那么movenext返回为true并且current被赋值为x,如果使用yield break使得movenext()返回false。