DEV Community

Cover image for MaterialPropertyBlock Prevents Material Duplication, So Why Does It Break the SRP Batcher?
Toàn Lương Bảo
Toàn Lương Bảo

Posted on Originally published at toanlb.dev on

MaterialPropertyBlock Prevents Material Duplication, So Why Does It Break the SRP Batcher?

MaterialPropertyBlock Prevents Material Duplication, So Why Does It Break the SRP Batcher?

In commercial Unity game production, the need to modify visual properties for individual objects at runtime arises across almost every system: highlighting interactive props on hover, shifting gear tint by rarity, triggering status visual states on characters, or animating opacity and dissolve thresholds on destructible scenery.

During the Built-in Render Pipeline era, one hard-earned lesson many Unity engineers internalized was to stop touching renderer.material. After encountering the Copy-on-Access trap of Renderer.material, which silently duplicates Material (Instance) assets and causes C++ native memory leaks, switching to MaterialPropertyBlock became standard practice. On the legacy pipeline, this kept memory flat, avoided creating orphaned material instances, and paired seamlessly with GPU Instancing.

However, once a project upgrades to the Universal Render Pipeline (URP) with the SRP Batcher enabled to reduce CPU overhead, an unexpected regression often surfaces. Groups of objects using MaterialPropertyBlock suddenly drop out of the SRP Batch. Opening Frame Debugger reveals hundreds of isolated draw calls flagged with MaterialPropertyBlock is used, while SetPass Call overhead on the CPU Render Thread climbs back up.

Why does a tool built specifically to preserve memory and batching clash directly with the SRP Batcher? And what practical alternatives exist in URP and Unity 6.3+ (6000.3) to customize per-object visuals without forfeiting SRP batching performance?


1. Under the Hood: Why MaterialPropertyBlock Conflicts with the SRP Batcher

To see the root cause of this conflict, we have to compare how MaterialPropertyBlock stores overrides against the CBUFFER architecture of the SRP Batcher inside GPU VRAM.

What MaterialPropertyBlock Actually Does

At its core, MaterialPropertyBlock does not duplicate a Material asset. Inside Unity's C++ engine layer, it is a lightweight key-value table attached directly to a Renderer component. Hundreds of objects continue pointing to the exact same sharedMaterial asset. Right before issuing a draw call for a specific object, the CPU reads the override values from that renderer's key-value block and uploads them to the GPU uniform state for that draw call.

In the Built-in Render Pipeline, this solved two major problems at once: zero RAM wasted on duplicated materials, zero orphaned native memory left behind after Destroy(gameObject), and direct compatibility with GPU Instancing uniform arrays.

The Split CBUFFER Design of the SRP Batcher

URP and HDRP take a fundamentally different approach to reducing CPU Render Thread overhead. Rather than merging meshes or packing uniform arrays per draw call, the SRP Batcher keeps constant buffers (CBUFFERs) resident in GPU VRAM and splits them into two strict memory domains:

  1. UnityPerMaterial: Stores all static material-level properties such as _BaseColor, _Smoothness, _Metallic, and texture Tiling/Offset. This buffer resides persistently in GPU VRAM. As long as the .mat asset properties remain unchanged, the CPU never re-packs or re-uploads material data each frame; it simply updates a memory offset pointer on the GPU.
  2. UnityPerDraw: Stores per-renderer instance data, including unity_ObjectToWorld, unity_WorldToObject, Lightmap ST, and Light Probe coefficients.
flowchart LR
    subgraph SG_SRP["Standard SRP Batcher Path (URP/HDRP)"]
        direction TB
        M1["Shared Material<br/>Cached persistently in UnityPerMaterial"]
        D1["Per-Renderer Data<br/>Only updates UnityPerDraw block"]
        R1["CPU shifts VRAM offset pointer<br/>Microsecond batch submission"]
        M1 --> R1
        D1 --> R1
    end
    subgraph SG_MPB["Broken Path with MaterialPropertyBlock"]
        direction TB
        M2["Attach MaterialPropertyBlock<br/>Overrides _BaseColor per Renderer"]
        D2["Breaks static UnityPerMaterial layout<br/>VRAM offset shortcut invalidated"]
        R2["Downgrades to Non-SRP Fallback<br/>CPU rebinds state every draw call"]
        M2 --> D2
        D2 --> R2
    end
    R1 -.->|"Call Renderer.SetPropertyBlock"| M2

Where the Collision Happens

In every SRP Batcher-compatible shader (such as Universal Render Pipeline/Lit), surface parameters like _BaseColor are strictly declared inside CBUFFER_START(UnityPerMaterial).

When you attach a MaterialPropertyBlock to a Renderer to override _BaseColor, your code forces a property defined as static at the material level (UnityPerMaterial) to become dynamic at the draw-call level (Per-Draw).

At that moment, the persistent UnityPerMaterial buffer layout cached in VRAM no longer matches the actual rendering state required by that object. The CPU Render Thread can no longer take the fast VRAM offset shortcut. Consequently, URP ejects that renderer from the SRP Batch and downgrades it to the legacy Non-SRP Batcher fallback path, forcing the CPU to gather and re-upload uniforms manually prior to drawing.

The Silent Trap of HasPropertyBlock() and Clear()

One subtle detail that frequently catches engineers off guard during URP profiling is the difference between MaterialPropertyBlock.Clear() and Renderer.SetPropertyBlock(null). Calling block.Clear() only clears the key-value entries stored inside the managed MaterialPropertyBlock instance (block.isEmpty == true); it does not detach the block from the underlying C++ Renderer.

If an effect finishes and the code only calls block.Clear() without detaching the block from the renderer, renderer.HasPropertyBlock() continues returning true, keeping the object evicted from SRP batches. To cleanly detach the override block and restore SRP Batcher compatibility, pass null explicitly:

using UnityEngine;

public static class PropertyBlockCleanupUtility
{
    public static void DetachPropertyBlock(Renderer targetRenderer)
    {
        if (targetRenderer != null && targetRenderer.HasPropertyBlock())
        {
            // Explicitly detach the PropertyBlock so the C++ Renderer re-enters the SRP Batcher
            targetRenderer.SetPropertyBlock(null);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Decision Tree and Practical Alternatives in URP

In URP and HDRP production code, no single technique covers every visual variation requirement. Selecting the right approach comes down to two constraints: whether the visual states are finite or continuously varying every frame, and whether the objects use MeshRenderer or SkinnedMeshRenderer.

flowchart TD
    Start["Need per-object visual variation in URP"] --> Q1{"Are the visual states finite?"}
    Q1 -->|"Finite (a few presets / states)"| A1["Swap SharedMaterial assets<br/>Preserves 100% SRP Batcher & SkinnedMesh"]
    Q1 -->|"Continuous per-frame variation"| Q2{"Same Mesh & Not SkinnedMesh?"}
    Q2 -->|"Yes (Grass, bullets, repeated props)"| A2["Use GPU Instancing<br/>Enable Instancing & UNITY_INSTANCING_BUFFER"]
    Q2 -->|"Mixed Meshes or Animator bones"| Q3{"Targeting Unity 6.3+ (6000.3)?"}
    Q3 -->|"Yes (Unity 6.3+)"| A3["Use SetShaderUserValue<br/>Read unity_RendererUserValue in SRP Batcher"]
    Q3 -->|"Older Unity version (incl. 6.0 LTS)"| A4["Use Vertex Color / UV channels<br/>Or isolate small Non-SRP groups"]

One critical detail on the GPU Instancing branch: in URP, the SRP Batcher takes precedence over GPU Instancing (checking Enable GPU Instancing on a Material is ignored while the SRP Batcher is active and no MPB is present). Once a MaterialPropertyBlock is attached, the object leaves the SRP Batcher and only enters the GPU Instancing batch if all three conditions are met simultaneously:

  1. Enable GPU Instancing is enabled on the Material (material.enableInstancing == true).
  2. The Shader declares #pragma multi_compile_instancing and places the overridden variable inside UNITY_INSTANCING_BUFFER_START/END instead of UnityPerMaterial.
  3. The objects share the exact same Mesh and Material (excluding standard SkinnedMeshRenderer without Vertex Animation Textures).

If any of these conditions is missing (such as overriding a property that still sits inside UnityPerMaterial via MPB), Frame Debugger drops the object into a slow Non-SRP Non-Instanced draw call.


3. Production Architecture and Verification with NUnit

Consider a stylized Action Adventure project running on URP, targeting a locked 60 FPS on mid-range mobile devices. The scene contains hundreds of interactive props (wooden crates, energy pylons, foliage clusters) alongside animated SkinnedMeshRenderer characters. During gameplay, these objects frequently transition across visual states (default, targeted highlight, damaged, frozen) or apply continuous per-object shader tinting on Unity 6.3 or newer.

Calling renderer.material would trigger progressive C++ native memory leaks as props spawn and despawn. Conversely, applying MaterialPropertyBlock across standard URP shaders would evict those objects from the SRP Batcher and spike CPU Render Thread frame time on mobile CPUs.

To solve this cleanly while keeping the core decision and packing logic independently testable outside a live graphics device, we can structure the orchestration around dedicated classes:

  1. SharedMaterialVariantPool<TState, TMaterial>: A custom pure C# mapping pool that binds finite visual states to pre-created Material references sharing the same Shader Variant. Zero runtime material cloning occurs, UnityPerMaterial stays intact, and SkinnedMeshRenderer objects remain fully batched.
  2. ShaderUserValueColorPacker: A custom pure C# bit-packing utility designed for Unity 6.3+'s SetShaderUserValue workflow (MeshRenderer.SetShaderUserValue / SkinnedMeshRenderer.SetShaderUserValue), packing 24-bit RGB color and an 8-bit normalized effect intensity into a single 32-bit uint delivered via unity_RendererUserValue inside UnityPerDraw.
  3. MaterialPipelineDescriptor and SrpBatcherCompatibilityAdvisor: Two custom pure C# classes that model renderer/material flags and audit whether a configuration stays on the SRP Batcher, transitions to GPU Instancing, or degrades to Non-SRP fallback.
  4. SrpSafeVisualPresenter: A custom MonoBehaviour presenter wrapping SharedMaterialVariantPool to swap sharedMaterial assets across all VisualState presets while explicitly stripping stale PropertyBlocks.

Below is the complete implementation alongside an NUnit [TestFixture] validating standard paths and edge cases:

using System;
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;

public enum VisualState
{
    Default = 0,
    Highlighted = 1,
    Damaged = 2,
    Frozen = 3
}

public enum RenderBatchingOutcome
{
    SrpBatcherActive,
    GpuInstancingActive,
    NonSrpFallbackPenalty
}

public sealed class MaterialPipelineDescriptor
{
    public bool IsSrpPipeline { get; }
    public bool IsShaderSrpBatcherCompatible { get; }
    public bool IsMaterialGpuInstancingEnabled { get; }
    public bool UsesInstancingBufferForOverride { get; }
    public bool HasMaterialPropertyBlock { get; }
    public bool IsSkinnedMesh { get; }

    public MaterialPipelineDescriptor(
        bool isSrpPipeline,
        bool isShaderSrpBatcherCompatible,
        bool isMaterialGpuInstancingEnabled,
        bool usesInstancingBufferForOverride,
        bool hasMaterialPropertyBlock,
        bool isSkinnedMesh)
    {
        IsSrpPipeline = isSrpPipeline;
        IsShaderSrpBatcherCompatible = isShaderSrpBatcherCompatible;
        IsMaterialGpuInstancingEnabled = isMaterialGpuInstancingEnabled;
        UsesInstancingBufferForOverride = usesInstancingBufferForOverride;
        HasMaterialPropertyBlock = hasMaterialPropertyBlock;
        IsSkinnedMesh = isSkinnedMesh;
    }
}

/// <summary>
/// Maps finite visual states to pre-allocated SharedMaterial references,
/// preserving SRP Batcher compatibility with zero runtime Material duplication.
/// </summary>
public sealed class SharedMaterialVariantPool<TState, TMaterial>
    where TState : notnull
    where TMaterial : class
{
    private readonly Dictionary<TState, TMaterial> _variants;
    private readonly TMaterial _fallbackMaterial;

    public SharedMaterialVariantPool(TMaterial fallbackMaterial)
    {
        if (fallbackMaterial == null)
        {
            throw new ArgumentNullException(nameof(fallbackMaterial));
        }

        _fallbackMaterial = fallbackMaterial;
        _variants = new Dictionary<TState, TMaterial>();
    }

    public int RegisteredCount => _variants.Count;

    public void RegisterVariant(TState state, TMaterial sharedMaterial)
    {
        if (sharedMaterial == null)
        {
            throw new ArgumentNullException(nameof(sharedMaterial));
        }

        _variants[state] = sharedMaterial;
    }

    public TMaterial ResolveMaterial(TState state)
    {
        if (_variants.TryGetValue(state, out TMaterial matched))
        {
            return matched;
        }

        return _fallbackMaterial;
    }
}

/// <summary>
/// Packs 24-bit RGB color and an 8-bit normalized intensity into a single 32-bit uint
/// for SetShaderUserValue (Unity 6.3+) without breaking the SRP Batcher.
/// </summary>
public static class ShaderUserValueColorPacker
{
    public static uint PackColorAndIntensity(Color32 color, float normalizedIntensity)
    {
        if (float.IsNaN(normalizedIntensity))
        {
            normalizedIntensity = 0f;
        }

        float clamped = normalizedIntensity < 0f ? 0f : (normalizedIntensity > 1f ? 1f : normalizedIntensity);
        byte intensityByte = (byte)Math.Round(clamped * 255f);

        return (uint)color.r
            | ((uint)color.g << 8)
            | ((uint)color.b << 16)
            | ((uint)intensityByte << 24);
    }

    public static void UnpackColorAndIntensity(uint packedValue, out Color32 color, out float normalizedIntensity)
    {
        byte r = (byte)(packedValue & 0xFF);
        byte g = (byte)((packedValue >> 8) & 0xFF);
        byte b = (byte)((packedValue >> 16) & 0xFF);
        byte intensityByte = (byte)((packedValue >> 24) & 0xFF);

        color = new Color32(r, g, b, 255);
        normalizedIntensity = intensityByte / 255f;
    }
}

/// <summary>
/// Evaluates SRP Batcher and GPU Instancing compatibility for a Renderer and Material setup under URP/HDRP.
/// </summary>
public sealed class SrpBatcherCompatibilityAdvisor
{
    public RenderBatchingOutcome EvaluateOutcome(MaterialPipelineDescriptor descriptor)
    {
        if (descriptor == null)
        {
            throw new ArgumentNullException(nameof(descriptor));
        }

        bool canUseGpuInstancing = !descriptor.IsSkinnedMesh
            && descriptor.IsMaterialGpuInstancingEnabled
            && descriptor.UsesInstancingBufferForOverride;

        if (!descriptor.IsSrpPipeline || !descriptor.IsShaderSrpBatcherCompatible)
        {
            return canUseGpuInstancing
                ? RenderBatchingOutcome.GpuInstancingActive
                : RenderBatchingOutcome.NonSrpFallbackPenalty;
        }

        // Attaching a MaterialPropertyBlock under URP/HDRP evicts the renderer from SRP Batching.
        if (descriptor.HasMaterialPropertyBlock)
        {
            return canUseGpuInstancing
                ? RenderBatchingOutcome.GpuInstancingActive
                : RenderBatchingOutcome.NonSrpFallbackPenalty;
        }

        return RenderBatchingOutcome.SrpBatcherActive;
    }
}

/// <summary>
/// Production MonoBehaviour component that swaps SharedMaterial assets by state
/// and strips stale PropertyBlocks so SRP Batching stays active.
/// </summary>
public sealed class SrpSafeVisualPresenter : MonoBehaviour
{
    [SerializeField] private Renderer _targetRenderer;
    [SerializeField] private Material _defaultMaterial;
    [SerializeField] private Material _highlightedMaterial;
    [SerializeField] private Material _damagedMaterial;
    [SerializeField] private Material _frozenMaterial;

    private SharedMaterialVariantPool<VisualState, Material> _pool;

    private void Awake()
    {
        if (_targetRenderer == null)
        {
            _targetRenderer = GetComponent<Renderer>();
        }

        if (_defaultMaterial == null && _targetRenderer != null)
        {
            _defaultMaterial = _targetRenderer.sharedMaterial;
        }

        if (_defaultMaterial == null)
        {
            Debug.LogError("[SrpSafeVisualPresenter] Missing Default Material or Renderer.", this);
            return;
        }

        _pool = new SharedMaterialVariantPool<VisualState, Material>(_defaultMaterial);
        if (_highlightedMaterial != null) _pool.RegisterVariant(VisualState.Highlighted, _highlightedMaterial);
        if (_damagedMaterial != null) _pool.RegisterVariant(VisualState.Damaged, _damagedMaterial);
        if (_frozenMaterial != null) _pool.RegisterVariant(VisualState.Frozen, _frozenMaterial);
    }

    public void ApplyState(VisualState state)
    {
        if (_targetRenderer == null || _pool == null)
        {
            return;
        }

        // Strip any residual PropertyBlock that would otherwise disable SRP Batching
        if (_targetRenderer.HasPropertyBlock())
        {
            _targetRenderer.SetPropertyBlock(null);
        }

        _targetRenderer.sharedMaterial = _pool.ResolveMaterial(state);
    }
}

[TestFixture]
public sealed class SrpBatcherVariantTests
{
    [Test]
    public void SharedMaterialVariantPool_WhenResolvingRegisteredAndUnknownStates_ReusesExactReferences()
    {
        object defaultMat = new object();
        object highlightMat = new object();
        object frozenMat = new object();

        var pool = new SharedMaterialVariantPool<VisualState, object>(defaultMat);
        pool.RegisterVariant(VisualState.Highlighted, highlightMat);
        pool.RegisterVariant(VisualState.Frozen, frozenMat);

        // Happy path: returns exact SharedMaterial references without cloning
        Assert.AreSame(highlightMat, pool.ResolveMaterial(VisualState.Highlighted));
        Assert.AreSame(frozenMat, pool.ResolveMaterial(VisualState.Frozen));

        // Boundary case: unregistered state falls back safely to default material
        Assert.AreSame(defaultMat, pool.ResolveMaterial(VisualState.Damaged));
        Assert.AreEqual(2, pool.RegisteredCount);
    }

    [Test]
    public void SharedMaterialVariantPool_WithNullArguments_ThrowsArgumentNullException()
    {
        Assert.Throws<ArgumentNullException>(() =>
        {
            _ = new SharedMaterialVariantPool<VisualState, object>(null);
        });

        var pool = new SharedMaterialVariantPool<VisualState, object>(new object());
        Assert.Throws<ArgumentNullException>(() =>
        {
            pool.RegisterVariant(VisualState.Damaged, null);
        });
    }

    [Test]
    public void ShaderUserValueColorPacker_WhenPackingAndUnpacking_PreservesChannelsAndHandlesBoundaries()
    {
        var inputColor = new Color32(180, 75, 240, 255);
        uint packed = ShaderUserValueColorPacker.PackColorAndIntensity(inputColor, 0.5f);

        ShaderUserValueColorPacker.UnpackColorAndIntensity(packed, out Color32 unpackedColor, out float unpackedIntensity);

        Assert.AreEqual(180, unpackedColor.r);
        Assert.AreEqual(75, unpackedColor.g);
        Assert.AreEqual(240, unpackedColor.b);
        Assert.AreEqual(0.5f, unpackedIntensity, 0.005f);

        // Boundary case: out-of-range or NaN values must clamp cleanly without byte corruption
        uint packedOver = ShaderUserValueColorPacker.PackColorAndIntensity(new Color32(10, 20, 30, 255), 1.8f);
        ShaderUserValueColorPacker.UnpackColorAndIntensity(packedOver, out _, out float overIntensity);
        Assert.AreEqual(1.0f, overIntensity, 0.001f);

        uint packedUnder = ShaderUserValueColorPacker.PackColorAndIntensity(new Color32(10, 20, 30, 255), -0.4f);
        ShaderUserValueColorPacker.UnpackColorAndIntensity(packedUnder, out _, out float underIntensity);
        Assert.AreEqual(0.0f, underIntensity, 0.001f);

        uint packedNaN = ShaderUserValueColorPacker.PackColorAndIntensity(new Color32(10, 20, 30, 255), float.NaN);
        ShaderUserValueColorPacker.UnpackColorAndIntensity(packedNaN, out _, out float nanIntensity);
        Assert.AreEqual(0.0f, nanIntensity, 0.001f);
    }

    [Test]
    public void SrpBatcherCompatibilityAdvisor_EvaluatesBatchingOutcomesAndNullInputAccurately()
    {
        var advisor = new SrpBatcherCompatibilityAdvisor();

        Assert.Throws<ArgumentNullException>(() =>
        {
            _ = advisor.EvaluateOutcome(null);
        });

        // Case 1: Clean URP setup without MPB -> SRP Batcher active (even on SkinnedMeshRenderer)
        var cleanSkinnedUrp = new MaterialPipelineDescriptor(
            isSrpPipeline: true,
            isShaderSrpBatcherCompatible: true,
            isMaterialGpuInstancingEnabled: false,
            usesInstancingBufferForOverride: false,
            hasMaterialPropertyBlock: false,
            isSkinnedMesh: true);
        Assert.AreEqual(RenderBatchingOutcome.SrpBatcherActive, advisor.EvaluateOutcome(cleanSkinnedUrp));

        // Case 2: MPB attached on standard URP Shader -> breaks SRP Batcher, enters fallback
        var brokenUrpWithMpb = new MaterialPipelineDescriptor(
            isSrpPipeline: true,
            isShaderSrpBatcherCompatible: true,
            isMaterialGpuInstancingEnabled: true,
            usesInstancingBufferForOverride: false,
            hasMaterialPropertyBlock: true,
            isSkinnedMesh: false);
        Assert.AreEqual(RenderBatchingOutcome.NonSrpFallbackPenalty, advisor.EvaluateOutcome(brokenUrpWithMpb));

        // Case 3: Repeated MeshRenderer meeting all 3 conditions -> batches via GPU Instancing
        var gpuInstancedMesh = new MaterialPipelineDescriptor(
            isSrpPipeline: true,
            isShaderSrpBatcherCompatible: true,
            isMaterialGpuInstancingEnabled: true,
            usesInstancingBufferForOverride: true,
            hasMaterialPropertyBlock: true,
            isSkinnedMesh: false);
        Assert.AreEqual(RenderBatchingOutcome.GpuInstancingActive, advisor.EvaluateOutcome(gpuInstancedMesh));

        // Boundary case: Missing Enable GPU Instancing on Material or Built-in without Instancing -> Non-SRP fallback
        var missingMaterialToggle = new MaterialPipelineDescriptor(
            isSrpPipeline: true,
            isShaderSrpBatcherCompatible: true,
            isMaterialGpuInstancingEnabled: false,
            usesInstancingBufferForOverride: true,
            hasMaterialPropertyBlock: true,
            isSkinnedMesh: false);
        Assert.AreEqual(RenderBatchingOutcome.NonSrpFallbackPenalty, advisor.EvaluateOutcome(missingMaterialToggle));

        var legacyNoInstancing = new MaterialPipelineDescriptor(
            isSrpPipeline: false,
            isShaderSrpBatcherCompatible: false,
            isMaterialGpuInstancingEnabled: false,
            usesInstancingBufferForOverride: false,
            hasMaterialPropertyBlock: true,
            isSkinnedMesh: false);
        Assert.AreEqual(RenderBatchingOutcome.NonSrpFallbackPenalty, advisor.EvaluateOutcome(legacyNoInstancing));
    }
}
Enter fullscreen mode Exit fullscreen mode

Reading SetShaderUserValue Inside HLSL on Unity 6.3+ (6000.3)

When targeting Unity 6.3 or newer and passing bit-packed integers from ShaderUserValueColorPacker via MeshRenderer.SetShaderUserValue(packed) or SkinnedMeshRenderer.SetShaderUserValue(packed) (note that this API is not available in Unity 6.0 LTS 6000.0), your custom HLSL shader or Shader Graph Custom Function node reads the value directly from unity_RendererUserValue without declaring anything inside UnityPerMaterial:

// Note: C# Color32 values are sRGB by default. In Linear Color Space (standard in URP),
// pass color.linear from C# or convert with SRGBToLinear() from Core.hlsl to prevent washed-out colors.
uint packed = unity_RendererUserValue;
float3 srgbTint = float3(
    (float)(packed & 0xFF),
    (float)((packed >> 8) & 0xFF),
    (float)((packed >> 16) & 0xFF)
) * (1.0 / 255.0);
float3 linearTint = SRGBToLinear(srgbTint);
float effectIntensity = (float)((packed >> 24) & 0xFF) * (1.0 / 255.0);
Enter fullscreen mode Exit fullscreen mode

Keep in mind that SetShaderUserValue is runtime-only (not serialized into scenes or prefabs) and evaluates to 0 under the Built-in Render Pipeline or during lightmap/light probe baking.


4. Engineering Trade-offs Matrix

No single per-object override strategy fits every scenario in URP. Here are the practical trade-offs across the four common approaches:

Comparison Criteria MPB on UnityPerMaterial Shader SharedMaterial Swapping GPU Instancing + MPB SetShaderUserValue (Unity 6.3+) / Vertex Color
Impact on SRP Batcher Evicts the object from SRP Batches Preserves 100% SRP Batching when sharing Shader Variant Leaves SRP Batcher; batches via GPU Instancing only if all 3 conditions hold Preserves 100% SRP Batching via UnityPerDraw / Mesh streams
Material Memory Allocation 0 duplicated Material instances Minimal (a few pre-created Material assets in memory) 0 duplicated Material instances 0 duplicated Material instances
SkinnedMeshRenderer Support Works, but incurs Non-SRP Fallback CPU penalty Full support while keeping SRP Batcher active Not natively supported without Vertex Animation Textures SetShaderUserValue in Unity 6.3+ directly supports SkinnedMeshRenderer
Parameter Flexibility Continuous per-frame variation on any property Limited to finite preset states (3 - 10 states) Continuous per-frame variation across identical meshes Constrained payload size (32-bit uint for SetShaderUserValue)
Shader Maintenance Cost Low, at the expense of CPU Render Thread overhead Very low; works out-of-the-box with standard URP shaders Moderate; requires Enable GPU Instancing and UNITY_INSTANCING_BUFFER Requires bit-packing, sRGB/Linear handling, or custom mesh/shader work
Best Production Fit Very few isolated objects with negligible CPU impact Character status presets, interaction highlights, finite states Dense identical meshes (foliage, projectiles, repeated props) Unity 6.3+ projects needing lightweight tint/intensity inside SRP Batcher

5. Production Takeaways for URP Projects

Moving from the Built-in Render Pipeline to URP means rethinking several optimization habits built over years of legacy Unity work:

  1. Do not carry Built-in habits blindly into URP: MaterialPropertyBlock was essential for avoiding renderer.material leaks on the Built-in Pipeline, yet in URP it silently turns off the SRP Batcher. Always verify the Rendering section inside Frame Debugger after introducing per-object shader overrides.
  2. Do not fear multiple SharedMaterial assets in URP: Unlike the legacy pipeline where every distinct Material risked a costly SetPass Call, the SRP Batcher processes dozens or hundreds of distinct Materials effortlessly as long as they share the same Shader Variant. For discrete visual states, swapping sharedMaterial references keeps memory clean and maintenance simple.
  3. Clear PropertyBlocks when returning objects to an Object Pool: If a pooled object ever receives a MaterialPropertyBlock, do not just call block.Clear(); explicitly call renderer.SetPropertyBlock(null) during pool reset. A lingering HasPropertyBlock() flag is enough to keep that renderer locked out of SRP batches for the remainder of the session.

Top comments (0)