I am trying to take a transparent screenshot. I have it like half the way there. The problem is that sometimes my RenderTexture has garbage in it. DiscardContents seems to do nothing. Right now I am trying to use GL.CLear which seems to work 50% of the time. Here is my method. How do I ensure the RenderTexture contents are always initially cleared?
private IEnumerator SaveScreenshotToFile(string fileName)
{
yield return null;
int resWidth = 1024;
int resHeight = 1024;
Camera camera = Camera.main;
RenderTexture rt = new RenderTexture(resWidth, resHeight, 32);
RenderTexture.active = rt;
yield return new WaitForEndOfFrame();
GL.Clear(false, true, Color.clear);
yield return new WaitForEndOfFrame();
RenderTexture.active = null;
camera.clearFlags = CameraClearFlags.Depth;
camera.targetTexture = rt;
yield return new WaitForEndOfFrame();
RenderTexture.active = rt;
Texture2D texture = new Texture2D(resWidth, resHeight, TextureFormat.ARGB32, false);
texture.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
camera.targetTexture = null;
RenderTexture.active = null;
byte[] bytes = texture.EncodeToPNG();
System.IO.File.Delete(fileName);
System.IO.File.WriteAllBytes(fileName, bytes);
return texture;
}