第一次用协程做读条时,我把它理解成“后台线程”。结果在协程里写了文件读写,编辑器直接卡住。后来才记住:Unity 协程跑在主线程上,yield 只是登记一个唤醒条件,把这一帧的控制权还回去。
几个常用的等待
yield return null:下一帧再继续。yield return new WaitForSeconds(t):按时间缩放等待。yield return new WaitForSecondsRealtime(t):不受 timeScale 影响,暂停菜单里更合适。yield return StartCoroutine(other):等另一个协程结束。
IEnumerator LoadSceneRoutine(string sceneName)
{
var op = SceneManager.LoadSceneAsync(sceneName);
op.allowSceneActivation = false;
while (op.progress < 0.9f)
{
SetProgress(op.progress);
yield return null;
}
SetProgress(1f);
op.allowSceneActivation = true;
}
它会在什么时候停
挂协程的行为被 Disable,或者物体被销毁,协程就会停。我曾经把加载协程写在会随 UI 一起关掉的面板上,面板一关,加载也中断了。后来把这类“跨界面流程”放到不会被随手关掉的常驻对象上。
备忘:StopCoroutine 要用 StartCoroutine 返回的句柄,或者同一个 IEnumerator 实例。只传方法名,遇到重载时很容易停错。