ReadPixels was called to read pixels from system frame buffer, while not inside drawing frame.[Unity3D][错误记录]

错误记录

为了场景上截图使用Texture2D 的ReadPixels 函数,出现了错误

正如下面的代码

1
2
3
4
Texture2D texture = new Texture2D (100, 100, TextureFormat.RGB24, false);
texture.ReadPixels (new Rect (0, 0, 32, 32), 0, 0, false);
texture.SetPixel (0, 0, Color.white);
texture.Apply ();

返回的错误是:
ReadPixels was called to read pixels from system frame buffer, while not inside drawing frame.

错误的意思很明显是渲染还没完成就截图屏幕,得到结果肯定是不完整的
那怎么办呢?

WaitForEndOfFrame

WaitForEndOfFrame会等待渲染完成在执行
这样你只要在ReadPixels前面加上WaitForEndOfFrame 就不会出现错误了。

1
2
3
4
5
6
Texture2D texture = new Texture2D (100, 100, TextureFormat.RGB24, false);
//等待渲染完成
yield return new WaitForEndOfFrame();
texture.ReadPixels (new Rect (0, 0, 32, 32), 0, 0, false);
texture.SetPixel (0, 0, Color.white);
texture.Apply ();

文章目录
  1. 1. 错误记录
    1. 1.1. 为了场景上截图使用Texture2D 的ReadPixels 函数,出现了错误
    2. 1.2. WaitForEndOfFrame
,