ReadPixels was called to read pixels from system frame buffer, while not inside drawing frame.
时间: 2024-03-06 09:47:11 浏览: 114
这个错误通常是因为尝试在渲染帧之外调用`ReadPixels`函数所导致的。Unity的渲染管线在每个帧之间进行同步,所以你必须在渲染帧时调用`ReadPixels`函数才能正确地读取像素数据。
为了解决这个问题,你可以将`ReadPixels`函数的调用移到`OnPostRender()`函数中。`OnPostRender()`函数是在每个Camera完成渲染之后调用的,因此在这里调用`ReadPixels`函数就可以保证它在渲染帧时被正确调用。以下是修改后的示例代码:
```
using UnityEngine;
public class ScreenRecorder : MonoBehaviour
{
public int captureWidth = 1920;
public int captureHeight = 1080;
public int captureFPS = 30;
public string fileName = "ScreenShot";
public bool isRecording = false;
private int frameCount = 0;
private Texture2D texture;
void Start()
{
Screen.SetResolution(captureWidth, captureHeight, false);
Time.captureFramerate = captureFPS;
}
void Update()
{
if (isRecording)
{
// Do something to start recording
}
}
void OnPostRender()
{
if (isRecording)
{
string path = Application.dataPath + "/" + fileName + "_" + frameCount.ToString("0000") + ".png";
texture = new Texture2D(captureWidth, captureHeight, TextureFormat.RGB24, false);
texture.ReadPixels(new Rect(0, 0, captureWidth, captureHeight), 0, 0);
texture.Apply();
byte[] bytes = texture.EncodeToPNG();
System.IO.File.WriteAllBytes(path, bytes);
frameCount++;
}
}
}
```
在这个修改后的示例中,我们将`ReadPixels`函数的调用移到了`OnPostRender()`函数中,并且在`Update()`函数中只是设置了一个标志来指示是否正在录制。这样做可以确保`ReadPixels`函数只在渲染帧时被调用,避免了上述错误的发生。
阅读全文