Unity中yield return null和yield return WaitForEndOfFrame的区别

4 篇文章 0 订阅
1 篇文章 0 订阅

测试结论:

1.如果只是等待下一帧执行,用yield return null即可。调用顺序在Update后,LateUpdate前

2.如果有截屏需要,用WaitForEndOfFrame。具体参考官方例子。否则直接用Texture2D.ReadPixel抓取屏幕信息则会报错。

3.此外,用WaitForEndOfFrame还可以让代码在LateUpdate的时序后调用。

using UnityEngine;
using System.Collections;
using System.IO;

public class Test1 : MonoBehaviour
{
    void OnEnable()
    {
        StartCoroutine(ReturnNullTest());
        StartCoroutine(ReturnWaitForEndOfFrame());
    }

    IEnumerator ReturnNullTest()
    {
        Debug.Log("[1] ReturnNull Frame Count: " + Time.frameCount + "Render Frame Count: " + Time.renderedFrameCount);
        yield return null;
        Debug.Log("[2] ReturnNull Frame Count: " + Time.frameCount + "Render Frame Count: " + Time.renderedFrameCount);
    }

    IEnumerator ReturnWaitForEndOfFrame()
    {
        Debug.Log("[1] WaitForEndOfFrame Frame Count: " + Time.frameCount + "Render Frame Count: " + Time.renderedFrameCount);
        yield return new WaitForEndOfFrame();
        Debug.Log("[2] WaitForEndOfFrame Frame Count: " + Time.frameCount + "Render Frame Count: " + Time.renderedFrameCount);
    }
}

从测试顺序来看,两者都可以达到下一帧执行的目的

但WaitForEndOfFrame的渲染帧会多跳一帧
在这里插入图片描述测试2:

先看一下官方的执行顺序表
在这里插入图片描述WaitForEndOfFrame会在一帧结束后调用,且在LateUpdate之后调用。

而正常yield return null的调用是在update之后,也就是说可以分别做到不同时序的调用。

public class Test : MonoBehaviour
{
    void Awake()
    {
        Debug.Log("0");
        StartCoroutine(TestCoroutine());
        Debug.Log("2");
    }

    void Update()
    {
        Debug.Log("3 - Update");
    }

    void LateUpdate()
    {
        Debug.Log("4 - LateUpdate");
    }

    IEnumerator TestCoroutine()
    {
        Debug.Log("1");
        yield return new WaitForEndOfFrame();
        Debug.Log("5");
    }
}

结果:
在这里插入图片描述不过对于静态置于场景中调用时,会多经过一次Update和LateUpdate

起初以为是第0帧问题,但后来放在Start中执行依旧会多经过一次。

但动态加载的prefab则没有该问题。

文献来源

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值