Cutout shader not being drawn on iOS

Hello,

I’m trying to make a simple cutout interface shader (with no lighting) for my project. It uses a variable named _Cutoff to decide which pixels to draw, and it uses the texture’s alpha channel to compare with the cutoff variable. If it passes, then it draws with 1 as its alpha; if not, it draws nothing. I tried doing this with pure Shaderlab by using AlphaTest; it worked fine on the editor but not on iOS. Then I tried to write a simple fragment shader for it, as you can see below:

Shader "GUI/Cutout" {
	Properties {
		_MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
		_Cutoff ("Alpha cutoff", Range(0,1)) = 0.5
	}

	SubShader {
		
		Tags { "Queue" = "Transparent" }
		Blend SrcAlpha OneMinusSrcAlpha
		ColorMask RGBA
		Cull Off
		Lighting Off
		ZWrite Off
		ZTest Always
		Fog { Mode Off }
		
		Pass {
			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag
			#include "UnityCG.cginc"

			float _Cutoff;
			sampler2D _MainTex;
			float4 _MainTex_ST;

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

			v2f vert (appdata_base v)
			{
				v2f o;
				o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
				o.uv = TRANSFORM_TEX (v.texcoord, _MainTex);
				return o;
			}

			half4 frag (v2f i) : COLOR
			{
				half4 texcol = tex2D (_MainTex, i.uv);
				if(texcol.a > _Cutoff) return half4(texcol.rgb, 1);
				else return half4(0, 0, 0, 0);
			}

			ENDCG
		}
	}
}

This works fine on the editor, but nothing at all is drawn on an iOS device. Any ideas of what I might be doing wrong? I’m using Unity 3.5.7.

Hi lixoman100

First, kudos for writing real shader code, this is very cool.

Here are a few suggestions

  1. Your shader is in the Queue “Transparent”. To do cutout effects (alpha testing) put your shader into the Queue “AlphaTest”. The Transparent Queue does traditional alpha blending, but it won’t do a real alpha test and clip pixels.

  2. You are on the right track with _Cutoff: this is a special keyword in Unity shaderland and will be necessary for your fallback shaders to work. That said-

  3. You need follow-up definitions of your shader variables. Unity shaders define their variables twice: once in the Properties block and then again in the code below. Add these lines between the Properties and SubShader block:

    CGINCLUDE

    uniform sampler2D _MainTex;

    uniform float _Cutoff;

    ENDCG

  4. Alongside your ZWrite, ZTest defines, add this:
    AlphaTest Greater [_Cutoff]

  5. Finally, at the very end of the shader, define a fallback shader. This will be important if your shader ever runs on hardware that can’t handle it–it will fall back to the shader you specify here. This is also crucial if you ever want shadows on your alpha cutout object.

Fallback “Transparent/Cutout/Diffuse”