Skip to content

Unity Shader – Transparency, ZWrite, ZTest, Blend

When implementing transparency in Unity you frequently see four switches—ZWrite, ZTest, Blend, Cull—and they’re easy to mix up. This note recaps the concepts and shows a two-pass approach for translucent objects that still occlude the rest of the scene properly.


1. Three transparency concepts

Alpha channel

  • Textures often pack opacity in the A channel
  • Fragment shaders read color.a as the transparency factor
  • You either perform alpha test or alpha blending

Alpha Test

Binary decision: draw or discard.

clip(alpha - _Cutoff);
// same as if (alpha < cutoff) discard;
  • Works with ZWrite On because surviving pixels are treated opaque
  • Produces crisp edges—great for foliage, fences, decals with holes

Alpha Blending

Classic translucency:

Dst = SrcAlpha * Src + (1 - SrcAlpha) * Dst

In ShaderLab:

Blend SrcAlpha OneMinusSrcAlpha
  • Requires ZWrite Off; otherwise the first layer writes depth and hides everything behind it

2. ZWrite

Controls whether the fragment writes to the depth buffer.

  • ZWrite On – depth stored, later fragments compare against it
  • ZWrite Off – no writes; draw order must be managed manually (usually back-to-front)

Typical combos:

  • Opaque: ZWrite On, ZTest LEqual
  • Transparent: ZWrite Off, Blend SrcAlpha OneMinusSrcAlpha

3. ZTest

Defines the comparison rule against the depth buffer.

  • Less, Greater, LEqual (default), Always, etc.
  • Most materials keep the default LEqual
  • Special effects like overlays/outlines may use Always

4. Problem: translucency + occlusion

Pure blending (ZWrite Off) looks transparent but doesn’t occlude later draws—objects can poke through.

Solution: two-pass transparency.

  1. Pass 1 – write depth only

    • ZWrite On
    • ColorMask 0 to avoid color writes
  2. Pass 2 – draw the translucent color

    • ZWrite Off
    • ZTest LEqual
    • Blend SrcAlpha OneMinusSrcAlpha
Pass {
    ZWrite On
    ColorMask 0
}

Pass {
    ZWrite Off
    ZTest LEqual
    Blend SrcAlpha OneMinusSrcAlpha
    // vertex/fragment programs
}

The first pass establishes correct depth; the second pass renders the color without overwriting depth, so other geometry still respects the silhouette. Downside: draws twice.


5. Takeaways

  • Alpha Test – binary cutout
  • Alpha Blending – true translucency, needs blending and usually ZWrite Off
  • ZWrite – whether we store depth
  • ZTest – how we compare against stored depth

Understanding these switches makes it easier to craft transparent, outline, or dissolve shaders.

Original article (Chinese) on CSDN “uniGame”, CC BY-SA 4.0.
https://blog.csdn.net/alla_Candy/article/details/121419479