Search code examples
unity-game-engineshaderfragment-shadervertex-shadercg

Why is this Shader producing a parse error when given as string to the Material constructor?


I wrote the following Shader:

Shader "Custom/SimpleShader" {
    Properties {
        _MainTex("Base (RGB)", 2D) = "white" { }
    }

    SubShader {
        Pass {
            ZTest Always
            Cull Off
            ZWrite Off

/* LINE 16*/CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"

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

            uniform sampler2D _MainTex;
            uniform sampler2D _Texture0;
            uniform fixed _Alpha0;

            v2f vert(appdata_img v)
            {
                v2f o;
                o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
                o.uv = MultiplyUV(UNITY_MATRIX_TEXTURE0, v.texcoord);
                o.uvb = MultiplyUV(UNITY_MATRIX_TEXTURE0, v.texcoord);
                return o;
            }

            fixed4 frag(v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);
                col.rgb += (tex2D(_Texture0, i.uvb).rgb * _Alpha0);
                return col;
            }

            ENDCG
        }
    }
    Fallback off
}

Unity tells me that there is a "Syntax Error" in line 16 (see mark). This happens, when I put this text into a string and give this string to the Material(string contents) constructor. However, when I put the text into a .shader file and import it in the normal way, the shader is accepted and does not produce an error.


Solution

  • This documentation concerning the Material(string contents) constructor (or rather its JavaScript counterpart) says that:

    [...] Creating materials this way supports only simple shaders (fixed function ones). If you need a surface shader, or vertex/pixel shaders, you'll need to create shader asset in the editor and use that.

    Thus, the answer is that fragment- and/or vertex-shaders are not supported this way.