Course contentsShow
← Unity Game Development
Lesson 616 of 8289. Rendering and VisualsFree lesson

Implementing Depth-Based Fog and Distance Fading

Use scene depth data to create custom fog effects or distance-based transitions that hide mesh edges in the environment.

In this lesson, you will learn how to leverage the scene depth buffer to dynamically fade your meshes into the background, creating atmospheric fog or seamless environmental transitions.

Understanding Depth Data

At this stage in your rendering journey, you’ve mastered PBR workflows and surface details, but objects often look "stuck" onto the scene. By accessing the Scene Depth node in Shader Graph, we can sample how far away a pixel is from the camera. This value (a normalized 0 to 1 float) becomes a powerful mask for blending your object’s base color with a distant fog color.

Implementing Distance Fading

To implement this, you’ll want to create a custom shader that compares the pixel’s depth to the camera’s Far Plane.

  1. Sample Scene Depth: Use the Scene Depth node (set to "Eye" space) to get the distance of the current fragment.
  2. Linearize/Remap: Subtract the Near Plane from your depth value and divide by the Far Plane to get a 0-1 linear gradient.
  3. Lerp Colors: Use this 0-1 value as the 'T' input in a Lerp node. The 'A' input is your object's original color (Albedo), and the 'B' input is your desired Fog color.

This simple math creates a "depth-based" transition where the object gradually dissolves into the background color as it reaches the horizon.

// Conceptually, your graph logic looks like this:
float depth = SceneDepth(ScreenPosition);
float fogFactor = saturate((depth - fogStart) / (fogEnd - fogStart));
float3 finalColor = lerp(objectColor, fogColor, fogFactor);

Hiding Mesh Edges

Beyond atmospheric fog, this technique is excellent for "dissolving" hard mesh edges. If you have objects floating in a void or modular pieces that don't quite align, using a softer, shorter-range depth fade creates a subtle blending effect. This hides the sharp polygon intersections, making your environment look like a cohesive, singular mass rather than a collection of distinct 3D models.

Key Takeaway: By using the Scene Depth node to drive a Lerp between your surface color and an environment-matched color, you can bridge the gap between distinct meshes and simulate atmospheric depth.