14 January 2012

Unity3d - Removing Render Texture alpha

 If you want to apply the Render Texture to a GUITexture object so it will be sized to the screen with other GUITexture objects. But GUITextures don't have indpendent materials or shaders so you won't be able to remove the alpha which is added to the render texture. Just setting the color of the GUITexture and the Render Texture camera to white and 100% still leaves the Render Texture transparent. So you can remove the alpha values from that render texture using the following script.




var alpha = 1.0;
private var mat : Material;

function Start ()
{
    mat = new Material(
        "Shader \"Hidden/Clear Alpha\" {" +
        "Properties { _Alpha(\"Alpha\", Float)=1.0 } " +
        "SubShader {" +
        "    Pass {" +
        "        ZTest Always Cull Off ZWrite Off" +
        "        ColorMask A" +
        "        SetTexture [_Dummy] {" +
        "            constantColor(0,0,0,[_Alpha]) combine constant }" +
        "    }" +
        "}" +
        "}"
    );
}

function OnPostRender()
{
    GL.PushMatrix();
    GL.LoadOrtho();
    mat.SetFloat( "_Alpha", alpha );
    mat.SetPass(0);
    GL.Begin( GL.QUADS );
    GL.Vertex3( 0, 0, 0.1 );
    GL.Vertex3( 1, 0, 0.1 );
    GL.Vertex3( 1, 1, 0.1 );
    GL.Vertex3( 0, 1, 0.1 );
    GL.End();
    GL.PopMatrix();

Apply this script to camera of whose render texture is to be taken.

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Nice workaround. I was having the same issue when i rendered terrain to a texture. Also, I posted a video on youtube for this and gave this blog credit. Let me know what you think: https://www.youtube.com/watch?v=V99V4IRl6D4

    ReplyDelete
  3. I'm really glad that my work could be of help and Thanks. Its nice that you made a video which explains things more clearly.

    ReplyDelete