In my game I generate some Texture2Ds in Start() which will be used for a Sprite Mask component. I want to clear those textures to a known value.
Here is the method I am using the clear the texture:
//Write every pixel of a texture to a specified value.
protected void ClearTexture(Texture2D tex, Color c)
{
//Use GL Clear to clear the texture to a known value
//GL.Clear only operates on the RenderTexture, so I have to change it,
//then change it back after copying it to the Texture2D.
//This is the same procedure as Blit
myFillColorMat.SetVector("_FillColor", c);
RenderTexture currentRT = RenderTexture.active;
RenderTexture target = RenderTexture.GetTemporary(tex.width,
tex.height,
0, RenderTextureFormat.ARGB32);
Debug.Log("ClearTexture with color " + c + " width " + tex.width + " height " + tex.height);
//GL.Clear(true, true, c);
Graphics.Blit(tex, target, myFillColorMat);
Graphics.CopyTexture(target, tex);
RenderTexture.active = currentRT;
RenderTexture.ReleaseTemporary(target);
}
The “myFillColorMat” is a material with a shader that just always returns _FillColor. The above code works and the Texture2D has the expected value.
When I instead tried to use GL.Clear to clear the texture (as commented-out above line 16), it appeared to have no noticeable effect on the Texture2D. Am I using GL.Clear incorrectly? The documentation says it is supposed to clear the renderTexture to the backgroundColor. The documentation also says that the operation may be limited by the active viewport, could that be the issue?