Using GL.Clear to clear a Texture2D to a specific color

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?

Well, yes :slight_smile: You probably should add a

GL.Viewport(new Rect(0f, 0f, tex.width, tex.height));

after you set your render texture active, which btw you’re currently don’t. Getting a temporary render texture does not automatically set it active. GL draw operations only affect the active rendertexture. Currently you save the old RT and restore it at the end, but you never change the active one :wink:

Ah, of course, thank you. Adding this line after getting the temporary RenderTexture allowed GL.Clear to work as expected:

RenderTexture.active = target;

It seemed to work without setting the Viewport, but I’ve added the line you suggested as well.