Question by
techmage · Oct 10, 2015 at 05:59 AM ·
rendertexturegl
Cannot get RenderTexture to clear garbage.
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;
}
Comment
Answer by paraself · Oct 10, 2015 at 10:49 AM
RenderTexture.active = rt;
yield return new WaitForEndOfFrame();
GL.Clear(false, true, Color.clear);
this part of your code actually does not work as you expected. Because in the end of the frame, RenderTexture.active is null rather than rt.
Doing yield return null or just not yield doesn't work either. There is still sometimes garbage in the transparent spaces.