在使用yield指令时,需要加上WaitForSeconds或者WaitForEndOfFrame等等,让协程等待一段时间再继续执行。代码示例如下:
IEnumerator ExampleCoroutine()
{
Debug.Log("Start of Coroutine");
yield return new WaitForSeconds(1f); //让协程等待1秒钟
Debug.Log("After 1 second");
yield return new WaitForEndOfFrame(); //等待当前帧结束
Debug.Log("End of Coroutine");
}
在这个例子中,协程会在开始时输出“Start of Coroutine”,等待1秒钟之后输出“After 1 second”,然后又等待一帧之后输出“End of Coroutine”。这样就避免了Unity在yield指令后停止PlayMode的问题。