协同程序和多线程有相似之处,但是又不是一个东西
协同程序是可以吧一个函数(routine) 分成几段执行,yield 关键字来等待协同程序的返回,
多线程在多核处理器的环境下能真正并行运行,协同程序任意时刻只有一个代码片段在运行
多线程要考虑线程同步,而协同程序不会,因为任意时刻只有一个协同程序的代码片段在运行
协同函数返回值必须是IEnumerator yield return 来返回
注意:4.3.1 最大允许协程数量为10000000个
1.用于定时器
启动1秒后debug输出
void Start () {
StartCoroutine(func()); //立即返回
//StartCoroutine("func");//立即返回
}
// Update is called once per frame
void Update () {
}
IEnumerator func()
{
yield return new WaitForSeconds(1);//暂停当前函数片段,让出给其他片段执行,等待WaitForXXXXXX 返回
Debug.Log("1111111");
}
2.加载进度显示
public Text txt;
// Use this for initialization
bool is_done;
int current;
int total;
void Start()
{
is_done = false;
current = 0;
total = 100;
txt = GameObject.Find("Text").GetComponent<Text>();
StartCoroutine(loding_sync());
// StartCoroutine( ()=>IEnumerator{} );
}
// Update is called once per frame
void Update()
{
}
IEnumerator loding_sync()
{
txt.text = "start to loaing";
yield return new WaitForSeconds(1.0f);
for (; current <= total; ++current)
{
yield return new WaitForEndOfFrame();
txt.text = current.ToString() + "%";
dosomethingelse();
}
txt.text = "Done";
}
void dosomethingelse()
{
}