I have a small bit of code i uses to perform a screen capture of my main camera.
Here’s most of the code i have in my ScreenshotManager on my main camera:
private Camera m_camera;
private bool m_takeScreenshotOnNextFrame = false;
[SerializeField]
private RawImage m_image;
private void OnPostRender()
{
if (m_takeScreenshotOnNextFrame)
{
m_takeScreenshotOnNextFrame = false;
RenderTexture renderTexture = m_camera.targetTexture;
Texture2D renderResult = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.ARGB32, false);
Rect rect = new Rect(0, 0, renderTexture.width, renderTexture.height);
renderResult.ReadPixels(rect, 0, 0);
byte[] byteArray = renderResult.EncodeToPNG();
System.IO.File.WriteAllBytes(Application.dataPath + "/TestScreen.png", byteArray);
Debug.Log("Saved Screen.");
m_image.texture = renderResult;
RenderTexture.ReleaseTemporary(renderTexture);
m_camera.targetTexture = null;
m_camera.cullingMask = m_camera.cullingMask | (1 << LayerMask.NameToLayer("UI"));
m_camera.fieldOfView = 60.0f;
}
}
private void TakeScreenshot(int width, int height)
{
m_camera.targetTexture = RenderTexture.GetTemporary(width, height, 16);
m_takeScreenshotOnNextFrame = true;
m_camera.cullingMask = m_camera.cullingMask & ~(1 << LayerMask.NameToLayer("UI"));
m_camera.fieldOfView = 50.0f;
}
This code works fine for exporting the screenshot as a PNG, but i can’t get it to work for displaying the texture on the UI with m_image. I’ve tried with RawImage and UIImage (with Sprite.Create) and both give me the same result: the image gets slightly, uniformly grey when i take the screenshot.
Here’s how my RawImage is set up, if that can help:
Any hint or advice on how i could get this to work is appreciated.