首页 > 解决方案 > WaitForEndOfFrame 在第一次运行时被调用两次

问题描述

我试图理解 WaitForEndOfFrame 并且几乎想通了,但问题是当yield遇到第一个时,它会跳过并将其保存到下一帧,并在下一帧中在渲染结束时恢复,但它被调用了两次,并且对于其余帧继续按预期工作。无法找出为什么yield在第二帧中调用了两次之后的预期代码。

void Update()
{
    print("1 - " + Time.frameCount);
    StartCoroutine(Enu());
    print("3 - " + Time.frameCount);
}

IEnumerator Enu()
{
    print("2 - " + Time.frameCount);
    yield return new WaitForEndOfFrame();
    print("4 - " + Time.frameCount);
}

1 - 1

2 - 1

3 - 1

--

1 - 2

2 - 2

3 - 2

4 - 2

4 - 2 <-- ?

--

1 - 3

2 - 3

3 - 3

4 - 3

--

1 - 4

2 - 4

3 - 4

4 - 4

--

1 - 5

2 - 5

3 - 5

4 - 5

标签: unity3dyield

解决方案


我会说它没有被调用两次,但是发生的事情是在第一帧开始的第一个协程一直持续到frameCount已经存在的第二帧内2


这似乎是与应用程序的第一帧相关的 Unity BUG !WaitForEndOfFrame

参见例如这篇文章(Dantus 的倒数第二个)

他们遇到了完全相同的问题,只是通过将当前frameCount作为参数传递给例程来更好地测试它,这样他们就知道它实际上在哪个帧继续:

public class WaitForEndTest : MonoBehaviour 
{      
     private void Update ()
     {  
         Debug.Log ("Update: " + Time.frameCount);
         StartCoroutine (WaitForEndOfFrameCoroutine (Time.frameCount));
     }
 
     private IEnumerator WaitForEndOfFrameCoroutine (int frameCount) 
     {
         Debug.Log ("Before end of frame: " + frameCount);
         yield return new WaitForEndOfFrame ();
         Debug.Log ("After end of frame: " + frameCount);
     }
}

这也为他们打印类似于你的情况

Update: 1
Before end of frame: 1
Update: 2
Before end of frame: 2
After end of frame: 1
After end of frame: 2

您应该在应用程序初始化期间将其视为 Unity 的一个小问题,并忽略它;)


推荐阅读