Monday, November 19, 2012

Creating a Colored Unlit Alpha Texture Shader for Unity

Last week I wrote about Creating a Colored Unlit Texture Shader for Unity.  I've used the shader from that post quite a lot on my new game Match'n Flip; however I recently realized it didn't work with alpha textures (textures with transparency).  So I decided to make a short post about creating the same kind of colored shader for a texture with alpha.

Applying a color combine with an alpha texture opens up some interesting possibilities, because you can control the opacity of the texture by modifying the color multiplier's alpha value.  Below is a picture of the default Unity Unlit Transparent shader, and on the right are 2 examples of my modified colored unlit transparent shader.  The opaque section of the object on the top right is semi-transparent because I set the color multiplier's alpha value to 50%(0.5), which the object on the bottom left is full opacity but has a red tint applied.


The shader itself is pretty simple, I modified Unity's Unlit-Alpha shader to support a Color property and handle the color combine operation.  The shader will appear in the shader dropdown menu under NAKAI/Unlit/Transparent Colored.  In case you're wondering, the Unlit-Alpha shader was written using Unity's ShaderLab Shader Syntax, I highly recommend reading up on the operations involved.  As before, you are free to copy and use this shader as you wish, Enjoy!

// Copied from Unlit-Alpha.shader, but adds color combine(tinting)
// Unlit alpha-blended shader.
// - no lighting
// - no lightmap support
// - Added per-material color

// Change this string to move shader to new location
Shader "NAKAI/Unlit/Transparent Colored" {
    Properties {
        // Adds Color field we can modify
        _Color ("Main Color", Color) = (1,1,1,1)
        _MainTex ("Base (RGB)", 2D) = "white" {}
    }
    
    SubShader {
        Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
        LOD 100
    
        ZWrite Off
        Blend SrcAlpha OneMinusSrcAlpha 

        Pass {
            Lighting Off
            SetTexture [_MainTex] { 
                // Sets _Color as the 'constant' variable
                constantColor[_Color]
                
                // Multiplies color (in constant) with texture
                combine constant * texture
            } 
        }
    }
}


2 comments: