Search code examples
c#imageunity-game-engineimage-processingscreenshot

How to have better colors with RenderTexture in unity?


I am using a script to do some screenshots in my game. However, I don't know much about color formats and stuff. The pictures it takes have less colors than the reality, especially on the transparent objects (some grey-transparent stuff are rendered black and less transparent).

Example : enter image description here enter image description here

Here is the code :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScreenshotManager : MonoBehaviour
{
    public Camera cam;

    IEnumerator Rend() 
    {
        yield return new WaitForEndOfFrame();
        RenderTexture renderTexture = cam.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();

        int screenshotIndex = 1;
        while(System.IO.File.Exists(Application.dataPath + "/Screenshot_" + screenshotIndex +".png"))
        {
            screenshotIndex++;
        }
        
        System.IO.File.WriteAllBytes(Application.dataPath + "/Screenshot_" + screenshotIndex +".png", byteArray);

        Debug.Log("Screen saved");

        RenderTexture.ReleaseTemporary(renderTexture);
        cam.targetTexture = null;
    }

    public void TakeScreenshot()
    {
        cam.targetTexture = RenderTexture.GetTemporary(Screen.width, Screen.height, 16);
        StartCoroutine(Rend());
    }
}

Am I missing something ?

Thanks for your help.


Solution

  • You can just use this function to take a screenshot

    ScreenCapture.CaptureScreenshot(fileName)
    

    Or in your case problem can be in RenderTextureFormat. Try to use RenderTextureFormat.ARGB64 if your camera use HDR

    RenderTexture.GetTemporary(Screen.width, Screen.height, RenderTextureFormat.ARGB64);