协程(一)基本使用
协程(二)协程什么时候调用
协程(三)IEnumerable、IEnumerator、foreach、迭代
协程(四)yield与迭代器
协程(五)简单模拟协程
协程(六)有关优化
一.yield return <expresion>含义
yield break:跳出协程操作,一般用在报错或者需要退出协程的地方。
yield: 协程将会在下一帧,所有Update函数后继续执行。
yield WaitForSeconds: 延迟指定时间后,协程在所有Update函数后面继续执行,时间使用Time.timeScale,
详细请参考:https://docs.unity3d.com/ScriptReference/WaitForSeconds.htmlWaitForSecondsRealtime:同上,使用未缩放的时间暂停协程执行····
yield WaitForFixedUpdate:在所有脚本上调用了FixedUpdate后继续执行。
WaitForEndOfFrame:在所有帧、相机、GUI渲染之后,显示在屏幕上之前。
详细请参考:https://docs.unity3d.com/ScriptReference/WaitForEndOfFrame.html
二.结合脚本生命周期
- 脚本生命周期参考:(https://www.jianshu.com/p/ea38ff4211a8)
-
您需要注意红色的地方
生命周期
生命周期
生命周期
三. 补充
- Start方法还可以写成这种
private IEnumerator Start()
{
yield return null;
}
四. 代码测试
- 以下代码可以帮助测试:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyText : MonoBehaviour
{
void Awake()
{
Debug.Log("Awake");
StartCoroutine(h1());
}
private void Start()
{
Debug.Log("Start");
}
private void FixedUpdate()
{
Debug.Log("FixedUpdate");
// StartCoroutine(h2());
}
private void Update()
{
Debug.Log("Update");
}
void LateUpdate()
{
Debug.Log("LateUpdate");
}
private void OnGUI()
{
Debug.Log("OnGUI");
}
private void OnApplicationQuit()
{
Debug.Log("OnApplicationPause");
}
private void OnDisable()
{
Debug.Log("OnDisable");
}
IEnumerator h1()
{
Debug.Log("h1");
yield return null;
Debug.Log("h2");
yield return null;
Debug.Log("h3");
yield return null;
Debug.Log("h4");
yield return null;
Debug.Log("h5");
yield return null;
Debug.Log("h6");
yield return null;
Debug.Log("h7");
yield return null;
Debug.Log("h8");
yield return null;
Debug.Log("h9");
yield return null;
Debug.Log("h10");
}
IEnumerator h2()
{
Debug.Log("h2");
yield return new WaitForFixedUpdate();
Debug.Log("h3");
}
}
参考资料:
https://docs.unity3d.com/Manual/CLIBatchmodeCoroutines.html
https://docs.unity3d.com/2019.3/Documentation/Manual/ExecutionOrder.html


