RenderTexture with transparent URP-based ShaderGraph auto-blends with black

I found this post going into some of the details of properly rendering transparent materials to and from RenderTextures, and it’s been incredibly helpful.

It turns out, the Transparent Alpha Blending-Mode URP ShaderGraph templates are all doing the correct thing, but it causes the RenderTexture to look incorrect when directly applied to a standard material, previewed in-editor, saved to a png texture, or sampled for color.

I’m not sure how to exactly describe the state of transparency and color in these results but they are only intermediate.
All you need to do is use any premultiply shader to then render the RenderTexture. Boom, looks perfect again.

So my shader was doing the correct thing in order to blend all along. You should start with a (0,0,0,0) black transparent background, the default state of a new RenderTexture. From there, multiple transparent ShaderGraph materials can be rendered to the texture over one another using: Graphics.Blit(null, renderTexture, material, 0);

The resulting image has everything blended together exactly as one would expect from alpha blending, It just needs to go through premultiply, so you’ll need a premultiply material, there are some options below.

Don’t be scared of shaders, be scared of ShaderGraph shaders. In my case, it’s way easier to write these simple 2D UI operations with Unity’s Base shaders and GPT’s help. They are likely way more performant too.

Options for premultiply material:

  • Regular Shader

  • Create a transparent unlit shader through Unity

  • Make sure it has Blend One OneMinusSrcAlpha, representing premultiply blending.

  • Create argument for a texture, ideally “_MainTex”

  • (this is 3 lines of code)

  • Frag method samples the texture: return tex2D(_MainTex, i.uv)

  • ShaderGraph

  • Setup a transparent ShaderGraph material using a premultiply alpha blending mode

  • Create Texture2D input, ideally, “MainTex”.

  • Sample Texture and return color & alpha

  • Old Legacy/Particles/Premultiply shader

  • search for “premultiply” in the shader drop-down in Inspector, under a material.

  • This seems to do okay for a quick test.

Verify original ShaderGraph uses alpha blending mode:

  • Save the Graph and select its asset in the Project pane

  • Click “Regenerate” or “View Generated Code” from the Inspector

  • Search for instances of "Blend "

  • Verify each instance uses Blend SrcAlpha OneMinusSrcAlpha, One OneMinusSrcAlpha

1 Like