【Unity性能优化】GPU数据回传Texture2D.ReadPixels VS AsyncGPUReadback

Unity中截取屏幕保存到本地时,会用到Texture2D.ReadPixels();

但Texture2D.ReadPixels()需要把数据从gpu传到cpu端,性能开销比较大,在某些低端机上会有明显的卡顿。

我们常常会有异步方法去改善这种卡顿:AsyncGPUReadback,

android端,在unity2019.4.30等某些版本上,AsyncGPUReadback依赖于图形API:Vulkan,而OpenGLES3下面是失败的(AsyncGPUReadbackRequest.hasError为true)

 int x = 0, y = 0 ,width = 256, height = 256;//其它来源
        Texture2D t2d = null;//其它来源
        RenderTexture rt = null;//其它来源
        if(SystemInfo.supportsAsyncGPUReadback)
        {
            AsyncGPUReadbackRequest req = AsyncGPUReadback.Request(rt, 0, x, width, y, height, 0, 1, TextureFormat.RGBA32);
            while(!req.done)
            {
                yield return null;
            }
            if(!req.hasError)
            {
                t2d.SetPixelData(req.GetData<Color32>(), 0);
                t2d.Apply();
            }
            else
            {
                Debug.LogError("Error AsyncGPUReadbackRequest.hasError");
            }
        }
        else
        {
            var oldRT = RenderTexture.active;
            RenderTexture.active = rt;
            t2d.ReadPixels(new Rect(_captureScreenScaleX, _captureScreenScaleY, _captureScreenScaleWidth, _captureScreenScaleHeight), 0, 0, false);
            t2d.Apply();
            RenderTexture.active = oldRT;
        }

猜你喜欢

转载自blog.csdn.net/PangNanGua/article/details/121256727
VS
今日推荐