uv not being passed through from vertex to surface shader


I’m getting up to scratch writing shaders in unity, and am trying to get the uv from the verts through to the surface shader. However for some reason when I declare a variable for the surface shader input named ‘uv_x’, it isn’t filled in with the uv from the mesh. To verify the uvs weren’t wrong, I tried just manually passing it through in a variable called ‘hello’ and get the expected result. This is my code (or a snippet of it)


		#pragma surface surf Lambert vertex:vert
		#pragma glsl
		#pragma target 3.0

		sampler2D _SDF_Texture;
		struct Input 
			float3 pos;
			float2 uv_sdf;
			float2 hello;

		void vert (inout appdata_full v, out Input OUT)

			//manually forcing through the uv value has no effect
			//OUT.uv_sdf = v.texcoord;

			//try passing uv value through just as a general parameter
			OUT.hello = v.texcoord;

		void surf (Input IN, inout SurfaceOutput o) 
			//always black (i.e. uv_sdf is always 0s)
			//float4 color = float4(IN.uv_sdf.x,IN.uv_sdf.y,0,1);

			//shows the colour gradient correctly across a quad (i.e. bl=black, tl=green, br=red, tr=yellow)
			float4 color = float4(IN.uv_sdf.x,IN.uv_sdf.y,0,1);

			o.Albedo = color.rgb;
			o.Alpha = 1.0;

I’m a little baffled. Manually forcing uv_sdf to be the right value has no effect, which suggests its being automatically overwritten with something, but not the uvs from the mesh. I tried explicitly marking uv_sdf as TEXCOORD0 but still no luck.

Anyone any thoughts on this one?



I’ve just spent the best part of a day figuring this out - I couldn’t find a version of this question with an answer, so I’ll attempt to answer it here: (Sorry this is 4 months late - I’m new to Unity)

First up you need to name your texture in your Input struct, with the format uv followed by TextureName:

float2 uv_MainTex;

You’ll then be able to access the UV coordinates in the surf struct and add an offset to sample MainTex in an alternate location, like this:

void surf (Input IN, inout SurfaceOutput o) {
       float2 offsetUVs = IN.uv_MainTex;
       offsetUVs.y += _adjustmentAmount;
       _surfaceColour = saturate(tex2D (_MainTex, offsetUVs).rgba * _offsetColour.rgba);

The tex2D method takes a sampler2D and a float2 as parameters, so you can make a change to the float2 from the input struct (IN.uv_MainTex) and pass the altered float2 into the tex2D method instead. I hope that works for you.