Yep, that error is Unity being picky about texture types, not your math.
Shader Graph is actually passing a typed texture (or even a UnityTexture2D wrapper), while the function I gave used the old untyped Texture2D. Let’s fix it so you can drop it in without complaints.
Use UnityTexture2D as input and the SAMPLE_TEXTURE2D macro.
In the Custom Function node, set the texture input type to Texture2D (Unity will wrap it as UnityTexture2D for the HLSL).
// 4-tap Sobel-like edge detection for a single channel
// For Unity Shader Graph Custom Function (file mode)
UnityTexture2D tex, // texture input (set as Texture2D in Shader Graph)
float2 texelSize, // 1.0 / resolution
out float edge // single-channel edge strength
// Diagonal samples (single channel: .r)
float s1 = SAMPLE_TEXTURE2D(tex.tex, tex.samplerstate, uv + texelSize * float2(-1.0, -1.0)).r; // top-left
float s2 = SAMPLE_TEXTURE2D(tex.tex, tex.samplerstate, uv + texelSize * float2( 1.0, 1.0)).r; // bottom-right
float s3 = SAMPLE_TEXTURE2D(tex.tex, tex.samplerstate, uv + texelSize * float2( 1.0, -1.0)).r; // top-right
float s4 = SAMPLE_TEXTURE2D(tex.tex, tex.samplerstate, uv + texelSize * float2(-1.0, 1.0)).r; // bottom-left
edge = sqrt(gx * gx + gy * gy);
Custom Function node (File mode):
- Source: your
Sobel4Tap.hlsl
- Function Name:
Sobel4Tap_float
Inputs (in this exact order):
tex – Texture2D
uv – Vector2
texelSize – Vector2
Outputs:
No separate sampler input is needed in this variant; it’s inside UnityTexture2D.
If your project is older / simpler and Shader Graph passes Texture2D<float4> instead, just change the parameter type:
float s1 = tex.Sample(texSampler, uv + texelSize * float2(-1.0, -1.0)).r;
float s2 = tex.Sample(texSampler, uv + texelSize * float2( 1.0, 1.0)).r;
float s3 = tex.Sample(texSampler, uv + texelSize * float2( 1.0, -1.0)).r;
float s4 = tex.Sample(texSampler, uv + texelSize * float2(-1.0, 1.0)).r;
edge = sqrt(gx * gx + gy * gy);
Inputs (Shader Graph):
tex – Texture2D
texSampler – SamplerState
uv – Vector2
texelSize – Vector2
Output: edge – Float
If you tell me which render pipeline & Unity version you’re on (URP/HDRP/Built-in), I can lock it exactly to that style, but one of the two above should immediately fix the “cannot convert from struct Texture2D / UnityTexture2D to Texture2D<float…>” error.