unity-game-enginefragment-shader

Unity shader make certain pixels transparent


I'm having an issue with my shader, specifically in the fragment function in the if statement. It should turn all white pixels transparent but they will just show as white.

This line in particular should set the alpha value to 0:

pixelColor.a = 0; // make pixel transparent

The rest of the code is working fine, I can change other properties of the white pixels, just not the alpha.

Shader "ARBI/WhiteToTransparent"
{
    Properties
    {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
    }

    SubShader
    {
        Tags { "Queue" = "Transparent" }
        LOD 200

        Pass
        {
            CGPROGRAM

            #pragma vertex vertexFunction
            #pragma fragment fragmentFunction
            #include "UnityCG.cginc"

            float4 _Color;
            sampler2D _MainTex;

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float4 position : SV_POSITION;
                float2 uv : TEXCOORD0;
            };

            v2f vertexFunction(appdata IN)
            {
                v2f OUT;

                OUT.position = UnityObjectToClipPos(IN.vertex);
                OUT.uv = IN.uv;

                return OUT;
            }

            fixed4 fragmentFunction(v2f IN) : SV_TARGET
            {
                fixed4 pixelColor = tex2D(_MainTex, IN.uv);

                // Check if the pixel is approximately white
                if (pixelColor.r > 0.99 && pixelColor.g > 0.99 && pixelColor.b > 0.99)
                {
                    pixelColor.a = 0; // make pixel transparent
                }

                return pixelColor;
            }

            ENDCG
        }
    }

    FallBack "Diffuse"
}

Solution

  • I, literally today, was having the same/similar problem. I hope this is what you are looking for. Some of my transparent pixels were showing as white. Getting rid of the .a should work.

    If pixels are white then turn the whole RGBA to 0 not just the alpha.

    
    if (pixelColor.r > 0.99 && pixelColor.g > 0.99 && pixelColor.b > 0.99)
                {
                    pixelColor = 0; // make pixel transparent
                }