Transparent Render Texture

Hi, Im creating icons for my assets (in the editor) to use in game. Im rendering the camera to a render texture and reading to a texture, the problem is that I dont know how to set the background to transparent. Is it possible? My camera background type is set to None and heres my code

        public Texture2D GetIconTexture()
        {          
            RenderTexture renderTexture = new RenderTexture(64, 64,32);
            Texture2D iconTexture = new Texture2D(64, 64, TextureFormat.RGBA32, false);
           
            cam.targetTexture = renderTexture;      
            RenderTexture.active = renderTexture;
            cam.Render();
            Rect rect = new Rect(0, 0, 64, 64);
            iconTexture.ReadPixels(rect, 0, 0);
            iconTexture.Apply();

            cam.targetTexture = null;
            RenderTexture.active = null;
            DestroyImmediate(renderTexture, false);
            return iconTexture;
        }

Thanks

You want to set the camera background to SolidColor, and use a color of 0,0,0,0.

Do note that the resulting icon will have a black outline if you have MSAA enabled, or if the image isn’t displayed at exactly 1:1 pixels to texels unless you disabled bilinear filtering. To fix that you’d need to use a premultipled alpha shader, which none of Unity’s built in shaders actual are (even the ones that call themselves premultiplied).

2 Likes