Game Development
Surface Shader
Learn the Surface Shader structure and #pragma surface.
Surface Shader Structure
Included in Unity's Built-in Render Pipeline, Surface Shaders automatically handle intricate lighting and shadow calculations on your behalf. Rather than writing low-level lighting math, you only define surface properties.
CGPROGRAM
#pragma surface surf Standard fullforwardshadows
#pragma target 3.0
ENDCG
The #pragma surface directive notifies the compiler of the surface function and lighting model to be used.
The surf Function and Surface Outputs
At the core of a Surface Shader is the surf function. It takes UV coordinates as input and fills out the SurfaceOutputStandard struct.
void surf (Input IN, inout SurfaceOutputStandard o)
{
o.Albedo = float3(1.0, 0.5, 0.2); // Base color
o.Metallic = 0.5; // Metallicness
o.Smoothness = 0.8; // Smoothness
}
Properties set here like Albedo and Smoothness are automatically illuminated by scene lights like Directional Light and Point Light.
Exercise Surface Shader lighting
Define a Start method. Inside, declare string aydinlatma = "Standard"; and print "Aydinlatma modeli: " + aydinlatma to the console.
Show example solution
using UnityEngine;
public class SurfaceLogger : MonoBehaviour
{
void Start()
{
string aydinlatma = "Standard";
Debug.Log("Aydinlatma modeli: " + aydinlatma);
}
}
Test yourself
-
Which compilation directive declares the surface function and the lighting model to use in a Surface Shader?
- #pragma surface surf Standard
- #pragma fragment frag
- #include "UnityCG.cginc"
- #define LIGHTING_ON
Show answer
#pragma surface surf Standard — The #pragma surface directive declares the surface function name (e.g. surf) and the lighting model (e.g. Standard) to the compiler.
-
Surface directive
#pragma ____ surf Standard fullforwardshadows
Show answer
#pragma surface surf Standard fullforwardshadows
-
Surface Shader elements
- #pragma surface
- Declares surface function and lighting
- surf
- Function populating surface properties
- Albedo
- Base diffuse color of the surface
- SurfaceOutputStandard
- Standard PBR lighting output struct
Next lesson: The Properties block