Unity 协程
1. 協程不是多線程,見官方圖,它發生在LateUpdate()之后的
2. 定義協程的方法,寫個方法,它必須返回IEnumerator 接口,可帶參數,也可以不帶參數;
3. 啟動協程StartCoroutine方法,
StartCoroutine("方法名")或StartCoroutine("方法名",相應的參數)
StarrtCoruntine(方法名())
4.停止協程
StopCoroutine("方法名"); 或StopAllCoroutines();
5.協程中常用的一些語句:
IEnumerator Test()
{
//等待下一幀Update之后,繼續執行后續代碼
yield return null;
//等待在所有相機和GUI渲染之后,直到幀結束,繼續執行后續代碼
yield return new WaitForEndOfFrame();
//等待下一個FixedUpdate之后,繼續執行后續代碼
yield return new WaitForFixedUpdate();
//等待3秒之后,繼續執行后續代碼,使用縮放時間暫停協程執行達到給定的秒數
yield return new WaitForSeconds(3.0f);
//等待3秒之后,繼續執行后續代碼,使用未縮放的時間暫停協程執行達到給定的秒數
yield return new WaitForSecondsRealtime(3.0f);
//等待直到Func返回true,繼續執行后續代碼
//yield return new WaitUntil(System.Func<bool>);
yield return new WaitUntil(() => true);
//等待直到Func返回false,繼續執行后續代碼
//yield return new WaitWhile(System.Func<bool>);
yield return new WaitWhile(() => false);
//等待新開啟的協程完成后,繼續執行后續代碼,可以利用這一點,實現遞歸
yield return StartCoroutine(Test());
//for循環
for (int i = 0; i < 10; i++)
{
Debug.Log(i);
yield return new WaitForSeconds(1);
}
//while循環,while(true):如果循環體內有yield return···語句,不會因為死循環卡死
int j = 0;
while (j < 10)
{
j++;
Debug.Log(j);
yield return new WaitForSeconds(1);
}
//終止協程
yield break;
}
總結
- 上一篇: ABAP GUI Text Edit
- 下一篇: 群辉 Docker-x64-17.05.