Skip to content

Instantly share code, notes, and snippets.

@hakanai
Last active July 7, 2023 11:51
Show Gist options
  • Save hakanai/2050a49993e1868eda0db58c43abf355 to your computer and use it in GitHub Desktop.
Save hakanai/2050a49993e1868eda0db58c43abf355 to your computer and use it in GitHub Desktop.
Reproduction of an annoying "feature" of surface shaders

Reproduces a dumb situation with Unity surface shaders where you try to use _MainTex_ST and find it is undefined. Then when you try to define it, you get told that it's a duplicate definition.

This appears to be "intended behaviour".

The attempted workaround, however, doesn't work for me. It compiles fine, but I just get black for the UVs.

The actual, viable workaround is to name the variables so they don't start with uv_ (so that Unity doesn't stomp them for you), and then populate them from a custom vertex shader.

Shader "Custom/BrokenSurfaceShader"
{
Properties
{
_MainTex ("Albedo (RGB)", 2D) = "white" {}
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 200
CGPROGRAM
#pragma surface surf Standard fullforwardshadows
#pragma target 3.0
sampler2D _MainTex;
// This is commented out so you get "undeclared identifier '_MainTex'"
// Uncomment this and you get "redefinition of '_MainTex'" instead.
// float4 _MainTex_ST;
struct Input
{
float2 uv_MainTex;
};
void surf (Input IN, inout SurfaceOutputStandard o)
{
float2 uv = IN.uv_MainTex * _MainTex_ST.xy;
o.Albedo = float3(uv, 0.0);
o.Metallic = 0.0;
o.Smoothness = 1.0;
o.Alpha = 1.0;
}
ENDCG
}
// FallBack "Diffuse"
}
Shader "Custom/BrokenSurfaceShaderAttemptedWorkaround"
{
Properties
{
_MainTex ("Albedo (RGB)", 2D) = "white" {}
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 200
CGPROGRAM
#pragma surface surf Standard fullforwardshadows
#pragma target 3.0
sampler2D _MainTex;
float4 _MainTex_ST;
struct Input
{
float2 uv_MainTexWorkaround;
};
void surf (Input IN, inout SurfaceOutputStandard o)
{
float2 uv = IN.uv_MainTexWorkaround * _MainTex_ST.xy;
o.Albedo = float3(uv, 0.0);
o.Metallic = 0.0;
o.Smoothness = 1.0;
o.Alpha = 1.0;
}
ENDCG
}
// FallBack "Diffuse"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment