Transparency in Camera RenderTexture

847 views Asked by At

In my Unity project, I'm working on rendering a view from a Camera to a Texture2D. I have created a RenderTexture to capture the Camera's output and then copied it to a Texture2D. However, I'm encountering an issue where I need the resulting image to have a transparent background. The only solution I have found so far is to set the Camera's background to transparent. However, I still have to specify a color, and this color becomes visible in all semi-transparent areas of the image.

Look at this.

In the white frame, you can see the final result obtained in the RenderTexture

Do you happen to know of any alternative methods to obtain a camera image with proper transparency?

Updated

Thank @mrVentures for the suggestion; I tried implementing it. A RenderTexture accumulates the image without clearing, so before copying it, it needs to be cleared and rendered for a single frame. Here's my code if anyone needs it.

public void clearTexture(RenderTexture texture) {
    RenderTexture.active = texture;
    GL.Clear(true, true, Color.clear);
    RenderTexture.active = null;

    // texture.Release();  — another option
}

public Texture2D getTextureFromCamera(Camera camera) {
    RenderTexture rt = camera.targetTexture;
    clearTexture(rt);
    viewCamera.Render();
    
    Texture2D tex = new Texture2D(rt.width, rt.height, TextureFormat.RGBA32, false);
    RenderTexture.active = rt;
    tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
    tex.Apply();
    RenderTexture.active = null;

    return tex;
}

Unfortunately, the result turned out exactly the same as when I had CameraClearFlags.Color with a black transparent background. As a result, the black semi-transparent shadows become even darker, and bright colors acquire a dark halo. This is far from the desired outcome.

The result

Do you have any other ideas I could try? I had the thought of obtaining the alpha channel separately and somehow baking the texture so that the semi-transparent areas of the image would be opaque. However, I have no idea how to accomplish that.

1

There are 1 answers

3
mrVentures On

Clear flags docs: https://docs.unity3d.com/ScriptReference/Camera-

CameraClearFlags.Nothing seems like what you want.