Unity: URP HLSL and Shader Graph
Everything in this course so far ran in a browser. In Unity, the same ideas are written in HLSL wrapped in Unity's ShaderLab file format, or built visually in Shader Graph. This lesson writes a real shader for the Universal Render Pipeline (URP), the default pipeline for new Unity 6 projects, and shows where each line of GLSL you know ends up.
Note: Shaders written for the old Built-in Render Pipeline (
CGPROGRAM,UnityCG.cginc,#pragma surface) do not work in URP. Most shader code you find online from before about 2020 is Built-in. URP shaders useHLSLPROGRAMand include files from the URP package instead.
The shape of a .shader file
A Unity shader file has three layers:
| Layer | What it holds | GLSL equivalent |
|---|---|---|
Shader "Path/Name" |
the name shown in the material's shader menu | none |
Properties { } |
values the material exposes in the Inspector | uniforms the host sets |
SubShader { Tags { } Pass { HLSLPROGRAM … ENDHLSL } } |
the actual GPU code, one block per pass | the vertex + fragment shader pair |
The smallest URP shader looks like this (create it with Assets > Create > Shader, then replace the contents):
Shader "Course/MinimalUnlit"
{
Properties { }
SubShader
{
Tags { "RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline" }
Pass
{
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
struct Attributes // vertex input (like GLSL "in" in a vertex shader)
{
float4 positionOS : POSITION; // object-space position
};
struct Varyings // vertex output = fragment input
{
float4 positionHCS : SV_POSITION; // clip-space position (gl_Position)
};
Varyings vert(Attributes IN)
{
Varyings OUT;
OUT.positionHCS = TransformObjectToHClip(IN.positionOS.xyz);
return OUT;
}
half4 frag() : SV_Target // SV_Target = the color output
{
return half4(0.9, 0.3, 0.2, 1.0);
}
ENDHLSL
}
}
}The "RenderPipeline" = "UniversalPipeline" tag means "use this SubShader only in URP". Core.hlsl brings in the URP shader library, including the space-transform functions such as TransformObjectToHClip, which does what projectionMatrix * viewMatrix * modelMatrix * position does in a GLSL vertex shader.
HLSL for GLSL writers
HLSL and GLSL are close cousins. The differences you will hit first:
| GLSL | HLSL |
|---|---|
vec2 vec3 vec4, mat4 |
float2 float3 float4, float4x4 (half4 = lower precision, like mediump) |
mix(a, b, t) |
lerp(a, b, t) |
fract(x) |
frac(x) |
mod(x, y) |
fmod(x, y) (sign follows x, unlike GLSL's mod) |
texture(tex, uv) |
SAMPLE_TEXTURE2D(tex, sampler_tex, uv) in URP (separate texture and sampler objects) |
M * v |
mul(M, v) (* on two matrices is component-wise) |
discard; |
clip(x) discards when x < 0 (discard; also exists) |
in/out variables |
structs with semantics (POSITION, TEXCOORD0, SV_POSITION, SV_Target) |
inversesqrt |
rsqrt |
atan(y, x) |
atan2(y, x) |
A textured, lit URP shader
Here is a complete shader with a texture, a tint color, simple Lambert lighting from the main directional light and ambient light from the scene's spherical harmonics. It is the Unity version of the Diffuse Lighting lesson.
Shader "Course/SimpleLit"
{
Properties
{
[MainTexture] _BaseMap ("Base Map", 2D) = "white" {}
[MainColor] _BaseColor ("Base Color", Color) = (1, 1, 1, 1)
_Wrap ("Wrap Lighting", Range(0, 1)) = 0
}
SubShader
{
Tags { "RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline" "Queue" = "Geometry" }
Pass
{
Name "ForwardLit"
Tags { "LightMode" = "UniversalForward" }
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
struct Attributes
{
float4 positionOS : POSITION;
float3 normalOS : NORMAL;
float2 uv : TEXCOORD0;
};
struct Varyings
{
float4 positionHCS : SV_POSITION;
float3 normalWS : TEXCOORD0; // any interpolated value uses a TEXCOORDn semantic
float2 uv : TEXCOORD1;
};
TEXTURE2D(_BaseMap);
SAMPLER(sampler_BaseMap);
// Every material property except textures goes in this buffer,
// so the SRP Batcher can batch draws that use this shader.
CBUFFER_START(UnityPerMaterial)
float4 _BaseMap_ST; // tiling (xy) and offset (zw) from the material
half4 _BaseColor;
half _Wrap;
CBUFFER_END
Varyings vert(Attributes IN)
{
Varyings OUT;
OUT.positionHCS = TransformObjectToHClip(IN.positionOS.xyz);
OUT.normalWS = TransformObjectToWorldNormal(IN.normalOS);
OUT.uv = TRANSFORM_TEX(IN.uv, _BaseMap);
return OUT;
}
half4 frag(Varyings IN) : SV_Target
{
half4 albedo = SAMPLE_TEXTURE2D(_BaseMap, sampler_BaseMap, IN.uv) * _BaseColor;
float3 n = normalize(IN.normalWS); // re-normalize after interpolation
Light mainLight = GetMainLight(); // direction (toward the light), color, attenuation
half ndotl = saturate((dot(n, mainLight.direction) + _Wrap) / (1.0 + _Wrap));
half3 diffuse = mainLight.color * ndotl;
half3 ambient = SampleSH(n); // ambient from the Lighting window / light probes
return half4(albedo.rgb * (diffuse + ambient), albedo.a);
}
ENDHLSL
}
}
}What each piece does:
Propertiesdeclares what the material Inspector shows. The names (_BaseMap,_BaseColor) must match the HLSL variables.[MainTexture]and[MainColor]tell Unity which propertiesMaterial.mainTextureandMaterial.colorrefer to."LightMode" = "UniversalForward"marks the pass that URP's forward renderer draws for lit opaque objects.TEXTURE2D/SAMPLER/SAMPLE_TEXTURE2Dare URP macros that expand to the right texture syntax on every graphics API Unity targets (D3D, Vulkan, Metal, OpenGL ES).CBUFFER_START(UnityPerMaterial)is the important one for performance. When all non-texture properties are in this constant buffer, the shader is SRP Batcher compatible: Unity can draw many objects with this shader without re-uploading material data per draw. The Inspector of a shader asset tells you whether it is compatible._BaseMap_STis filled in automatically with the material's Tiling and Offset;TRANSFORM_TEXapplies it.GetMainLight()comes fromLighting.hlsl. It returns aLightstruct withdirection,color,distanceAttenuationandshadowAttenuation.
What this shader does not do yet, compared with URP's own Lit shader: receive shadows (needs #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE and a shadow coordinate), cast shadows (needs a ShadowCaster pass), additional lights, fog and the depth passes (DepthOnly, DepthNormals) that features such as SSAO and the depth prepass read. A custom shader without those passes still draws, but the object will not cast shadows or appear in the depth texture. For a full PBR surface, copying URP's Lit features by hand is a big job; that is where Shader Graph shines.
The same shader in Shader Graph
Shader Graph is Unity's node editor for shaders. It generates all the passes (shadows, depth, motion vectors) for you, so most game teams use it for surface materials and write HLSL by hand only for special cases.
To rebuild the shader above:
- In the Project window, Create > Shader Graph > URP > Lit Shader Graph and open it.
- In the Blackboard, add a Texture2D property (
Base Map) and a Color property (Base Color). Drag them into the graph. - Add a Sample Texture 2D node, connect
Base Mapto its Texture input, and multiply its RGBA output byBase Colorwith a Multiply node. - Connect the result to Base Color in the Fragment block of the Master Stack. The Lit target does the lighting (full PBR, shadows, all lights) itself.
- For custom lighting (like the wrap term above), use an Unlit Shader Graph and compute the light yourself, or put HLSL in a Custom Function node, which calls a function from an
.hlslfile or inline code. - Save, then create a material from the graph (right-click the graph asset, Create > Material).
Rough mapping between the two:
| HLSL | Shader Graph |
|---|---|
Properties + CBUFFER |
Blackboard properties (Shader Graph builds the CBUFFER for you) |
SAMPLE_TEXTURE2D |
Sample Texture 2D node |
lerp, saturate, dot |
Lerp, Saturate, Dot Product nodes |
_Time.y |
Time node |
clip(alpha - threshold) |
Graph Settings: Alpha Clipping, plus the Alpha and Alpha Clip Threshold outputs |
| a helper function | Sub Graph, or a Custom Function node |
Tip: Even if you only use Shader Graph, you can read the HLSL it generates: select the graph asset and use View Generated Shader in the Inspector. It is the fastest way to learn how URP's real passes are structured.
Unity-specific gotchas
- Time is
_Timein HLSL:_Time.yis seconds (likeiTime),_Time.xis seconds / 20,_Time.zseconds × 2,_Time.wseconds × 3. - Color properties are converted to linear when the project uses Linear color space (the default for new projects), so the value you read in HLSL is not the sRGB number you typed. See Field Notes.
- Shader variants multiply: every
multi_compilekeyword doubles (or more) the number of compiled versions. Prefershader_featurefor material toggles; it only keeps the variants that materials actually use in a build. - Unity's clip space follows the platform (D3D-style 0..1 depth on most platforms, reversed Z). Use the
Transform…functions and theUNITY_REVERSED_Zmacro instead of assuming OpenGL conventions.
Unity's course covers the editor side of materials, and One Dissolve, Three Engines builds a full effect in this style.
Test yourself
Why put material properties inside CBUFFER_START(UnityPerMaterial) in a URP shader?
- It is required for textures to work
- It makes the shader compatible with the SRP Batcher
- It enables shadows
- It converts colors to linear space
Which HLSL function corresponds to GLSL's mix?
- blend
- lerp
- mad
- smoothstep
Your hand-written URP shader draws fine but the object casts no shadow. What is missing?
- A ShadowCaster pass
- The RenderType tag
- A Properties block
- The SV_Target semantic