協(xié)程是什么?
協(xié)程是一個分部執(zhí)行,遇到條件(yield return 語句)會掛起,直到條件滿足才會被喚醒繼續(xù)執(zhí)行后面的代碼。
通俗點說:程序內(nèi)部可中斷,然后轉(zhuǎn)而執(zhí)行別的子程序,在適當?shù)臅r候再返回來接著執(zhí)行。
協(xié)程的運行
協(xié)程不是線程,也不是異步執(zhí)行的。協(xié)程和 MonoBehaviour 的 Update函數(shù)一樣也是在MainThread中執(zhí)行的。
協(xié)同程序可以和主程序并行運行,和多線程有點類似。
協(xié)程的作用
1、延時(等待)一段時間執(zhí)行代碼;
2、等某個操作完成之后再執(zhí)行后面的代碼。
總結(jié)起來就是一句話:控制代碼在特定的時機執(zhí)行。

Paste_Image.png
協(xié)程的定義
在C#中,協(xié)程返回值必須是Ienumerator,yield要用yield return 來替代,并且啟動協(xié)同程序用StartCoroutine 函數(shù)
yield 和 IEnumerator都是C#的東西,他們是一個關(guān)鍵字,StartCoroutine是枚舉類的接口。

Paste_Image.png
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
public class xiecheng : MonoBehaviour
{
void Start()
{
StartCoroutine(One());//開啟協(xié)成
for (int i = 0; i < 200; i++)//循環(huán)A
{
Debug.Log("————" + i);
Thread.Sleep(10);
}
}
IEnumerator One()
{
for (int i = 0; i < 100; i++)//循環(huán)B
{
Debug.Log("***********" + i);
}
yield return new WaitForSeconds(1f);//協(xié)程1
for (int i = 0; i < 100; i++)//循環(huán)C
{
Debug.Log("$$$$$$$$$$" + i);
yield return null;//協(xié)程1
}
}
void Update()
{
Debug.Log("upda");
}
void LateUpadate()
{
Debug.Log("------LateUpadate");
}
}
運行結(jié)果:先執(zhí)行循環(huán)B,然后執(zhí)行循環(huán)A,然后執(zhí)行update()和lateUpdate()的方法,等待1S之后,在updat()和lateupda()之間執(zhí)行循環(huán)C的輸出。