Search Unity

undeclared identifier "_MatColor"?

Discussion in 'Shaders' started by candlemaster, Mar 12, 2015.

  1. candlemaster

    candlemaster

    Joined:
    Mar 12, 2014
    Posts:
    16
    So, I'm pretty new to writing shaders for Unity, but not new to writing shaders in general, and I'm getting a rather strange error. Basically, here is my source code:

    Code (CG):
    1. Shader "Custom/ToonCharacter"
    2. {
    3.     Properties
    4.     {
    5.         _MatColor ("Material Color", Color) = (1,1,1,1)
    6.         _UnlitColor ("Shading Color", Color) = (0.5, 0.5, 0.5, 1)
    7.         _SpecColor ("Highlight Color", Color) = (1, 1, 1, 1)
    8.         _LightThreshold ("Light Threshold", Range(-1, 1) ) = 0.1
    9.         _SpecThreshold ("Specular Threshold", Range(0.5, 1) ) = 1
    10.         _Shininess ("Shininess", Range(0, 1) ) = 0.5
    11.         _OutlineColor ("Outline Color", Color) = (0, 0, 0, 0)
    12.         _OutlineThick ("Outline Thickness", Range(0, 1) ) = 0.1
    13.         _MainTex ("Texture (RGB)", 2D) = "white" {}
    14.     }
    15.     SubShader
    16.     {
    17.         Pass
    18.         {
    19.             // Tags { "LightMode" = "ForwardBase" }
    20.             // Pass for ambient light and first light source
    21.            
    22.             CGPROGRAM
    23.            
    24.             // Tells the cg to use a vertex-shader called vert
    25.             #pragma vertex vert
    26.             // Tells the cg to use a fragment-shader called frab
    27.             #pragma fragment frag
    28.            
    29.             //= User-Defined =\\
    30.             uniform float4 _MatColor;
    31.             uniform float4 _UnlitColor;
    32.             uniform float4 _SpecColor;
    33.             uniform float _LightThreshold;
    34.             uniform float _SpecThreshold;
    35.             uniform float _Shininess;
    36.             uniform float4 _OutlineColor;
    37.             uniform float _OutlineThick;
    38.            
    39.             //= UNITY-Defined =\\
    40.             uniform float4 _LightColor0;
    41.             uniform sampler2D _MainTex;
    42.             uniform float4 _MainTex_ST;
    43.            
    44.             struct vertexInput
    45.             {
    46.                 float4 vertex : POSITION;
    47.                 float3 normal : NORMAL;
    48.                 float2 texcoord : TEXCOORD0;
    49.             };
    50.            
    51.             struct vertexOutput
    52.             {
    53.                 float4 pos : SV_POSITION;
    54.                 float3 normalDir : TEXCOORD1;
    55.                 float4 lightDir : TEXCOORD2;
    56.                 float3 viewDir : TEXCOORD3;
    57.                 float2 uv : TEXCOORD0;
    58.             };
    59.            
    60.             vertexOutput vert(vertexInput input)
    61.             {
    62.                 vertexOutput output;
    63.                
    64.                 // normal direction
    65.                 output.normalDir = normalize(mul(float4(input.normal, 0.0), _World2Object).xyz);
    66.                
    67.                 // World position
    68.                 float4 posWorld = mul(_Object2World, input.vertex);
    69.                
    70.                 // View direction
    71.                 output.viewDir = normalize(_WorldSpaceCameraPos.xyz - posWorld.xyz); // vector from object to the camera
    72.                
    73.                 // Light direction
    74.                 float3 fragmentToLightSource = (_WorldSpaceCameraPos.xyz - posWorld.xyz);
    75.                 output.lightDir = float4(
    76.                     normalize(lerp(_WorldSpaceLightPos0.xyz, fragmentToLightSource, _WorldSpaceLightPos0.w) ),
    77.                     lerp(1.0, 1.0/length(fragmentToLightSource), _WorldSpaceLightPos0.w)
    78.                 );
    79.                
    80.                 // output to fragment
    81.                 output.pos = mul(UNITY_MATRIX_MVP,input.vertex);
    82.                 output.uv = input.texcoord;
    83.             }
    84.            
    85.             float4 frag(vertexOutput input) : COLOR
    86.             {
    87.                 float nDotL = saturate(dot(input.normalDir, input.lightDir.xyz));
    88.                
    89.                 // Diffuse threshold calculation
    90.                 float diffuseCutoff = saturate((max(_LightThreshold, nDotL) - _LightThreshold) * 1000);
    91.                 // Specular threshold calculation
    92.                 float specularCutoff = saturate(max(_Shininess, dot(reflect(-input.lightDir.xyz, input.normalDir), input.viewDir)) - _Shininess) * 1000;
    93.                
    94.                 // Calculate Outlines
    95.                 float outlineStrength = saturate((dot(input.normalDir, input.viewDir) - _OutlineThick) * 1000);
    96.                
    97.                 float3 ambientLight = (1-diffuseCutoff) * _UnlitColor.xyz;
    98.                 float3 diffuseReflection = (1-specularCutoff) * _MatColor.xyz * diffuseCutoff;
    99.                 float3 specularReflection = _specColor.xyz * specularCutoff;
    100.                
    101.                 float3 texColor = tex2D(_MainTex, input.uv);
    102.                 float3 combinedLight = ((ambientLight * texColor) + diffuseReflection) * outlineStrength + specularReflection;
    103.                
    104.                 return float4(combinedLight, 1.0)//; + tex2D(_mainTex, input.uv);
    105.             }
    106.            
    107.             ENDCG
    108.         }
    109.     }
    110.     FallBack "Diffuse"
    111. }
    112.  
    I get the error "Shader error in 'Custom/ToonCharacter': undeclared identifier '_MatColor' at line 98 (on d3d11)". I have no idea why this is. _MatColor is clearly defined, I can see it right at the top in both the properties and in the pass.

    What's going on here?

    I'm using Unity 5, btw.
     
  2. pixpusher2

    pixpusher2

    Joined:
    Oct 30, 2013
    Posts:
    121
    Did a quick check, apparently the backslash "\\" in your line 29 comment is causing the error. Just remove them (also on line 39) and the _MatColor error will go away.

    Few other fixes:
    Code (CSharp):
    1. line 82: needs a "return output;" at the end of this function
    2. line 99: _specColor.xyz needs to be _SpecColor.xyz (capital S)
    3. line 104: semi colon ";" was commented out. Just add it back in
    Cheers
     
    kcfos likes this.
  3. Farfarer

    Farfarer

    Joined:
    Aug 17, 2010
    Posts:
    2,249
    I suspect you want #include UnityCG.cginc in there at least, too.
     
  4. candlemaster

    candlemaster

    Joined:
    Mar 12, 2014
    Posts:
    16
    The backslashes were the issue. Thanks pixpusher2!
     
  5. Farfarer

    Farfarer

    Joined:
    Aug 17, 2010
    Posts:
    2,249
    For what it's worth, in some languages a backslash at the end of a comment tells the compiler to also ignore the following line. I suspect that's why it was causing issues.
     
  6. candlemaster

    candlemaster

    Joined:
    Mar 12, 2014
    Posts:
    16
    I think that the backslash was telling the compiler to ignore the "newline" that immediately followed, so the compiler thought that the next line was part of the same comment. Even though MonoDevelop didn't show that...
     
  7. Audace

    Audace

    Joined:
    Jul 7, 2014
    Posts:
    1
    I have the same problem with a different script, but no backslash error in my code. Can you help me?

    Code (CSharp):
    1. Shader "Custom/Grass Geometry Shader" {
    2.     Properties{
    3.         _BottomColor("Bottom Color", Color) = (0,1,0,1)
    4.         _TopColor("Top Color", Color) = (1,1,0,1)
    5.         _GrassHeight("Grass Height", Float) = 1
    6.         _GrassWidth("Grass Width", Float) = 0.06
    7.         _RandomHeight("Grass Height Randomness", Float) = 0.25
    8.         _WindSpeed("Wind Speed", Float) = 100
    9.         _WindStrength("Wind Strength", Float) = 0.05
    10.         _Radius("Interactor Radius", Float) = 0.3
    11.         _Strength("Interactor Strength", Float) = 5
    12.         _Rad("Blade Radius", Range(0,1)) = 0.6
    13.         _BladeForward("Blade Forward Amount", Float) = 0.38
    14.         _BladeCurve("Blade Curvature Amount", Range(1, 4)) = 2
    15.         _AmbientStrength("Ambient Strength",  Range(0,1)) = 0.5
    16.         _MinDist("Min Distance", Float) = 40
    17.         _MaxDist("Max Distance", Float) = 60
    18.     }
    19.  
    20.  
    21.         CGINCLUDE
    22. #include "UnityCG.cginc"
    23. #include "Lighting.cginc"
    24. #include "AutoLight.cginc"
    25. #pragma multi_compile _SHADOWS_SCREEN
    26. #pragma multi_compile_fwdbase_fullforwardshadows
    27. #pragma multi_compile_fog
    28. #define GrassSegments 5 // segments per blade
    29. #define GrassBlades 4 // blades per vertex
    30.  
    31.         struct v2g
    32.     {
    33.         float4 pos : SV_POSITION;
    34.         float3 norm : NORMAL;
    35.         float2 uv : TEXCOORD0;
    36.         float3 color : COLOR;
    37.  
    38.  
    39.     };
    40.  
    41.     struct g2f
    42.     {
    43.         float4 pos : SV_POSITION;
    44.         float3 norm : NORMAL;
    45.         float2 uv : TEXCOORD0;
    46.         float3 diffuseColor : COLOR;
    47.         float3 worldPos : TEXCOORD3;
    48.         LIGHTING_COORDS(5, 6)
    49.             UNITY_FOG_COORDS(4)
    50.     };
    51.  
    52.     half _GrassHeight;
    53.     half _GrassWidth;
    54.     half _WindSpeed;
    55.     float _WindStrength;
    56.     half _Radius, _Strength;
    57.     float _Rad;
    58.  
    59.     float _RandomHeight;
    60.     float _BladeForward;
    61.     float _BladeCurve;
    62.  
    63.     float _MinDist, _MaxDist;
    64.  
    65.     uniform float3 _Positions[100];
    66.     uniform float _PositionArray;
    67.  
    68.     v2g vert(appdata_full v)
    69.     {
    70.         float3 v0 = v.vertex.xyz;
    71.  
    72.         v2g OUT;
    73.         OUT.pos = v.vertex;
    74.         OUT.norm = v.normal;
    75.         OUT.uv = v.texcoord;
    76.         OUT.color = v.color;
    77.         return OUT;
    78.     }
    79.  
    80.     float rand(float3 co)
    81.     {
    82.         return frac(sin(dot(co.xyz, float3(12.9898, 78.233, 53.539))) * 43758.5453);
    83.     }
    84.  
    85.     // Construct a rotation matrix that rotates around the provided axis, sourced from:
    86. // https://gist.github.com/keijiro/ee439d5e7388f3aafc5296005c8c3f33
    87.     float3x3 AngleAxis3x3(float angle, float3 axis)
    88.     {
    89.         float c, s;
    90.         sincos(angle, s, c);
    91.  
    92.         float t = 1 - c;
    93.         float x = axis.x;
    94.         float y = axis.y;
    95.         float z = axis.z;
    96.  
    97.         return float3x3(
    98.             t * x * x + c, t * x * y - s * z, t * x * z + s * y,
    99.             t * x * y + s * z, t * y * y + c, t * y * z - s * x,
    100.             t * x * z - s * y, t * y * z + s * x, t * z * z + c
    101.             );
    102.     }
    103.  
    104.     // hack because TRANSFER_VERTEX_TO_FRAGMENT has harcoded requirement for 'v.vertex'
    105.     struct unityTransferVertexToFragmentHack
    106.     {
    107.         float3 vertex : POSITION;
    108.     };
    109.  
    110.     // per new grass vertex
    111.     g2f GrassVertex(float3 vertexPos, float width, float height, float offset, float curve, float2 uv, float3x3 rotation, float3 faceNormal, float3 color, float3 worldPos) {
    112.         g2f OUT;
    113.         OUT.pos = UnityObjectToClipPos(vertexPos + mul(rotation, float3(width, height, curve) + float3(0, 0, offset)));
    114.         OUT.norm = faceNormal;
    115.         OUT.diffuseColor = color;
    116.         OUT.uv = uv;
    117.         OUT.worldPos = worldPos;
    118.  
    119.         // send extra vertex to forwardadd pass
    120.         unityTransferVertexToFragmentHack v;
    121.         v.vertex = vertexPos + mul(rotation, float3(width, height, curve) + float3(0, 0, offset));
    122.         TRANSFER_VERTEX_TO_FRAGMENT(OUT);
    123.         UNITY_TRANSFER_FOG(OUT, OUT.pos);
    124.         return OUT;
    125.     }
    126.  
    127.     // wind and basic grassblade setup from https://roystan.net/articles/grass-shader.html
    128.     // limit for vertices
    129.     [maxvertexcount(51)]
    130.     void geom(point v2g IN[1], inout TriangleStream<g2f> triStream)
    131.     {
    132.         float3 sphereDisp;
    133.  
    134.         float forward = rand(IN[0].pos.yyz) * _BladeForward;
    135.         float3 lightPosition = _WorldSpaceLightPos0;
    136.  
    137.         float3 perpendicularAngle = float3(0, 0, 1);
    138.         float3 faceNormal = cross(perpendicularAngle, IN[0].norm) * lightPosition;
    139.  
    140.         float4 worldPos = mul(unity_ObjectToWorld, IN[0].pos);
    141.  
    142.         // camera distance for culling
    143.         float distanceFromCamera = distance(worldPos, _WorldSpaceCameraPos);
    144.         float distanceFade = 1 - saturate((distanceFromCamera - _MinDist) / _MaxDist);
    145.  
    146.         float3 v0 = IN[0].pos.xyz;
    147.  
    148.         float3 wind1 = float3(sin(_Time.x * _WindSpeed + v0.x) + sin(_Time.x * _WindSpeed + v0.z * 2) + sin(_Time.x * _WindSpeed * 0.1 + v0.x), 0,
    149.             cos(_Time.x * _WindSpeed + v0.x * 2) + cos(_Time.x * _WindSpeed + v0.z));
    150.  
    151.         wind1 *= _WindStrength;
    152.  
    153.         // Interactivity
    154.         for(int i = 0; i < _PositionArray; i++)
    155.         {
    156.             float3 dis = distance(_Positions[i], worldPos); // distance for radius
    157.             float3 radius = 1 - saturate(dis / _Radius); // in world radius based on objects interaction radius
    158.             spehereDisp = worldPos - _Positions[i]; // position comparison
    159.             sphereDisp *= radius; // position multiplied by radius for falloff
    160.             sphereDisp = clamp(sphereDisp.xyz * _Strength, -0.8, 0.8); // increase strength
    161.         }
    162.  
    163.         // set vertex color
    164.         float3 color = (IN[0].color);
    165.         // set grass height
    166.         _GrassHeight *= IN[0].uv.y;
    167.         _GrassWidth *= IN[0].uv.x;
    168.         _GrassHeight *= clamp(rand(IN[0].pos.xyz), 1 - _RandomHeight, 1 + _RandomHeight);
    169.  
    170.         // grassblades geometry
    171.         for (int j = 0; j < (GrassBlades * distanceFade); j++)
    172.         {
    173.             // set rotation and radius of the blades
    174.             float3x3 facingRotationMatrix = AngleAxis3x3(rand(IN[0].pos.xyz) * UNITY_TWO_PI + j, float3(0, 1, -0.1));
    175.             float3x3 transformationMatrix = facingRotationMatrix;
    176.             float radius = j / (float)GrassBlades;
    177.             float offset = (1 - radius) * _Rad;
    178.             for (int i = 0; i < GrassSegments; i++)
    179.             {
    180.                 // taper width, increase height;
    181.                 float t = i / (float)GrassSegments;
    182.                 float segmentHeight = _GrassHeight * t;
    183.                 float segmentWidth = _GrassWidth * (1 - t);
    184.  
    185.                 // the first (0) grass segment is thinner
    186.                 segmentWidth = i == 0 ? _GrassWidth * 0.3 : segmentWidth;
    187.  
    188.                 float segmentForward = pow(t, _BladeCurve) * forward;
    189.  
    190.                 // Add below the line declaring float segmentWidth.
    191.                 float3x3 transformMatrix = i == 0 ? facingRotationMatrix : transformationMatrix;
    192.  
    193.                 // first grass (0) segment does not get displaced by interactivity
    194.                 float3 newPos = i == 0 ? v0 : v0 + ((float3(sphereDisp.x, sphereDisp.y, sphereDisp.z) + wind1) * t);
    195.  
    196.                 // every segment adds 2 new triangles
    197.                 triStream.Append(GrassVertex(newPos, segmentWidth, segmentHeight, offset, segmentForward, float2(0, t), transformMatrix, faceNormal, color, worldPos));
    198.                 triStream.Append(GrassVertex(newPos, -segmentWidth, segmentHeight, offset, segmentForward, float2(1, t), transformMatrix, faceNormal, color, worldPos));
    199.  
    200.  
    201.  
    202.             }
    203.             // Add just below the loop to insert the vertex at the tip of the blade.
    204.             triStream.Append(GrassVertex(v0 + float3(sphereDisp.x * 1.5, sphereDisp.y, sphereDisp.z * 1.5) + wind1, 0, _GrassHeight, offset, forward, float2(0.5, 1), transformationMatrix, faceNormal, color, worldPos));
    205.             // restart the strip to start another grass blade
    206.             triStream.RestartStrip();
    207.         }
    208.     }
    209.  
    210.  
    211.     ENDCG
    212.         SubShader
    213.     {
    214.         Cull Off
    215.  
    216.             Pass // basic color with directional lights
    217.             {
    218.                 Tags
    219.                 {
    220.                     "RenderType" = "Geometry"
    221.                     "LightMode" = "ForwardBase"
    222.                 }
    223.  
    224.             CGPROGRAM
    225.             #pragma vertex vert
    226.             #pragma fragment frag
    227.             #pragma geometry geom
    228.             #pragma target 4.6
    229.             #pragma multi_compile_fwdbase_fullforwardshadows
    230.  
    231.             float4 _TopColor;
    232.             float4 _BottomColor;
    233.             float _AmbientStrength;
    234.  
    235.             float4 frag(g2f i) : SV_Target
    236.             {
    237.                 // take shadow data
    238.             float shadow = 1;
    239. #if defined(SHADOWS_SCREEN)
    240.             shadow = (SAMPLE_DEPTH_TEXTURE_PROJ(_ShadowMapTexture, UNITY_PROJ_COORD(i._ShadowCoord)).r);
    241. #endif          
    242.             // base color by lerping 2 colors over the UVs
    243.             float4 baseColor = lerp(_BottomColor , _TopColor , saturate(i.uv.y)) * float4(i.diffuseColor, 1);
    244.             // multiply with lighting color
    245.             float4 litColor = (baseColor * _LightColor0);
    246.             // multiply with vertex color, and shadows
    247.             float4 final = litColor * shadow;
    248.             // add in basecolor when lights turned off
    249.             final += saturate((1 - shadow) * baseColor * 0.2);
    250.             // add in ambient color
    251.             final += (unity_AmbientSky * baseColor * _AmbientStrength);
    252.             // add fog
    253.             UNITY_APPLY_FOG(i.fogCoord, final);
    254.             return final;
    255.             }
    256.             ENDCG
    257.         }
    258.  
    259.             Pass
    260.                 // point lights
    261.             {
    262.                 Tags
    263.                 {
    264.                     "LightMode" = "ForwardAdd"
    265.                 }
    266.                 Blend OneMinusDstColor One
    267.                 ZWrite Off
    268.  
    269.             CGPROGRAM
    270.             #pragma vertex vert
    271.             #pragma geometry geom
    272.             #pragma fragment frag                                  
    273.             #pragma multi_compile_fwdadd_fullforwardshadows
    274.  
    275.             float4 frag(g2f i) : SV_Target
    276.             {
    277.                     UNITY_LIGHT_ATTENUATION(atten, i, i.worldPos);
    278.  
    279.                     float3 pointlights = atten * _LightColor0.rgb;
    280.  
    281.                     return float4(pointlights, 1);
    282.                 }
    283.             ENDCG
    284.             }
    285.  
    286.         Pass // shadow pass
    287.             {
    288.                 Tags
    289.                 {
    290.                     "LightMode" = "ShadowCaster"
    291.                 }
    292.  
    293.                     CGPROGRAM
    294.                     #pragma vertex vert
    295.                     #pragma geometry geom
    296.                     #pragma fragment frag
    297.                     #pragma multi_compile_shadowcaster
    298.  
    299.                     float4 frag(g2f i) : SV_Target
    300.                     {
    301.  
    302.                         SHADOW_CASTER_FRAGMENT(i)
    303.                     }
    304.                     ENDCG
    305.             }
    306.  
    307.  
    308.     }    Fallback "VertexLit"
    309. }
    310.