CodeBlanks Logo Icon CodeBlanks

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.

Practice Surface Shader lighting

Define a Start method. Inside, declare string aydinlatma = "Standard"; and print "Aydinlatma modeli: " + aydinlatma to the console.

Starter code

Player.cs
using UnityEngine;

public class SurfaceLogger : MonoBehaviour
{
    // Start icinde aydinlatma degiskenini tanimla ve yazdir
}

Sample solution

Player.cs
using UnityEngine;

public class SurfaceLogger : MonoBehaviour
{
    void Start()
    {
        string aydinlatma = "Standard";
        Debug.Log("Aydinlatma modeli: " + aydinlatma);
    }
}

Expected output

Aydinlatma modeli: Standard

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which compilation directive declares the surface function and the lighting model to use in a Surface Shader?

  • #pragma surface surf Standard Correct answer
  • #pragma fragment frag
  • #include "UnityCG.cginc"
  • #define LIGHTING_ON

Explanation: The #pragma surface directive declares the surface function name (e.g. surf) and the lighting model (e.g. Standard) to the compiler.

2 Surface directive

Question
#pragma ____ surf Standard fullforwardshadows
Answer
#pragma surface surf Standard fullforwardshadows

Explanation: The '#pragma surface' keyword is used in surface shader declarations.

3 Surface Shader elements

Term Meaning
#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

All lessons in Advanced