How to render a 3D object with various alpha into a render texture, such that the alpha is maintained

I have setup a render camera with alpha 0 clear setting.
The render texture target is 32 bit RGBA
I have a 3D object with a 32bit alpha texture ( think of a holey object, where the holes are alpha 0, not geometry holes )
I render the 3D object into the texture… if I use a standard opaque shader like Legacy/Diffuse, the result is as expected… the render texture has alpha edges from the camera clear, with my object in the middle, but the alpha holes don’t show through onto the render texture.
So the render texture has both alpha 1 and alpha 0 areas. So far so good.

If I render my with an alpha shader, then it renders into the render texture, using the alpha channel does indeed cut holes, and whatever color the camera clear’s color is set to… shows through the holes.

BUT.
it dies not “RENDER” the alpha from my 3D object’s texture into the render texture. So I cannot use that texture in the scene like a sprite, or like just rendering the 3D object would look.

Summary.

  1. rendering diffuse/non transparent shader into the render texture, writes alpha 1 into it (regardless of the alpha in the texture or shader’s output)
  2. rendering with alpha transparent shader into the render texture, uses the alpha to control how visible the texture is rendered into the render texture, but does not render the Alpha into the texture’s A channel. The A channel is just 100% zero.

How do I make the shader write the RGB and “A” into the render texture please? (not from the camera clear, but from the shader render)
This should be possible. I’ve tried various shader blend and op modes… with no luck.
Help appreciated. Thanks in advance

the problem is most of the shaders don’t concern alpha channel. some just ignore the alpha channel (in the source code, some of them includes code “ColorMask RGB”, which ignore alpha channel). other render on alpha with insuitable blending.

I think the ultimate solution is to use Camera.RenderWithShader() with a custom shader that only renders alpha channel

ok found the solution… saw many other previous searches so hopefully this will help some others also.
The Unity Lambert lighting overrides what the Blends modes say to do, and wipes out the alpha assuming that you don’t want it. ( you can look at the compiled shader code to see this )
If you want to write your alpha to the render texture, then add the magic keyword ‘keepalpha’

	 #pragma surface surf Lambert keepalpha	

It doesn’t hurt to specify alphamask rgba either

	  ColorMask RGBA

can also remind user to use RGBA in the shader’s texture field…

_MainTex("Texture (RGBA)", 2D) = "white" {}