TExcelTAD
Home › Unity with C# › Profiler, Frame Debugger & Batching

Profiler, Frame Debugger & Batching

"The game is slow" is not something you can fix. "EnemyAI.Update takes 6 ms on 300 enemies, 4 ms of it in GetComponent" is. Unity's profiling tools turn the first sentence into the second. Measure before you optimize, and measure on the target device: the editor adds overhead, and a phone is not your desktop.

The tools

Tool Open with Answers
Profiler Window > Analysis > Profiler where CPU time goes per frame (scripts, physics, rendering, GC), GPU time, memory, audio
Frame Debugger Window > Analysis > Frame Debugger every draw call of one frame, in order, and why batches were broken
Memory Profiler (package com.unity.memoryprofiler) Window > Analysis > Memory Profiler snapshots of all memory: textures, meshes, managed objects, leaks between two snapshots
Profile Analyzer (package) Window > Analysis > Profile Analyzer compares captures: did the change help over 300 frames?
Rendering Debugger Window > Analysis > Rendering Debugger URP overdraw, lighting and material debug views

Using the Profiler

  1. Make a Development Build with Autoconnect Profiler ticked (in the build profile), run it on the device, and select it in the Profiler's target drop-down. Profile the editor only for quick checks.
  2. Record a few seconds of the slow part, click a spike in the CPU Usage chart, and switch the bottom pane to Hierarchy, sorted by Total or Self ms.
  3. Look at the GC Alloc column: anything allocating every frame is a candidate for the next lesson.
  4. Deep Profile instruments every C# call: precise but very slow. Prefer adding your own markers.
csharp
using Unity.Profiling;
using UnityEngine;

public class CrowdSystem : MonoBehaviour
{
    static readonly ProfilerMarker s_Steer = new("Crowd.Steer");
    static readonly ProfilerMarker s_Avoid = new("Crowd.Avoid");

    void Update()
    {
        using (s_Steer.Auto())          // shows up as "Crowd.Steer" in the Profiler hierarchy
        {
            Steer();
        }
        using (s_Avoid.Auto())
        {
            Avoid();
        }
    }

    void Steer() { /* ... */ }
    void Avoid() { /* ... */ }
}

Markers cost almost nothing, work in development builds, and are compiled out of release builds.

The frame budget

At 60 FPS a frame has 16.67 ms for everything: scripts, physics, animation, rendering and the GPU. At 30 FPS, 33.3 ms. On mobile, aim well below the budget to avoid thermal throttling. The model reads a set of sampled frame timings, the kind of numbers the Profiler's hierarchy shows, finds the frames over budget and the biggest cost in each:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Linq;

const double Budget = 1000.0 / 60;
var frames = new List<Dictionary<string, double>>
{
    new() { ["Scripts"] = 4.1, ["Physics"] = 2.0, ["Animation"] = 1.2, ["Render"] = 5.5, ["GC.Collect"] = 0.0 },
    new() { ["Scripts"] = 4.3, ["Physics"] = 2.1, ["Animation"] = 1.2, ["Render"] = 5.6, ["GC.Collect"] = 0.0 },
    new() { ["Scripts"] = 4.2, ["Physics"] = 2.0, ["Animation"] = 1.3, ["Render"] = 5.4, ["GC.Collect"] = 7.9 },
    new() { ["Scripts"] = 9.8, ["Physics"] = 2.2, ["Animation"] = 1.2, ["Render"] = 5.5, ["GC.Collect"] = 0.0 },
    new() { ["Scripts"] = 4.0, ["Physics"] = 6.5, ["Animation"] = 1.2, ["Render"] = 5.6, ["GC.Collect"] = 0.0 },
};

Console.WriteLine(
quot;budget {Budget:F2} ms"); for (int i = 0; i < frames.Count; i++) { double total = frames[i].Values.Sum(); var worst = frames[i].MaxBy(kv => kv.Value); string flag = total > Budget ?
quot;OVER by {total - Budget:F2} ms, biggest: {worst.Key} {worst.Value:F1} ms" : "ok"; Console.WriteLine(
quot;frame {i + 1}: {total,5:F2} ms {flag}"); } var avg = frames.SelectMany(f => f).GroupBy(kv => kv.Key) .Select(g => (Name: g.Key, Ms: g.Average(kv => kv.Value))).OrderByDescending(x => x.Ms); Console.WriteLine("average per system: " + string.Join(", ", avg.Select(a =>
quot;{a.Name} {a.Ms:F2}")));
budget 16.67 ms
frame 1: 12.80 ms  ok
frame 2: 13.20 ms  ok
frame 3: 20.80 ms  OVER by 4.13 ms, biggest: GC.Collect 7.9 ms
frame 4: 18.70 ms  OVER by 2.03 ms, biggest: Scripts 9.8 ms
frame 5: 17.30 ms  OVER by 0.63 ms, biggest: Physics 6.5 ms
average per system: Render 5.52, Scripts 5.28, Physics 2.96, GC.Collect 1.58, Animation 1.22

Averages hide spikes: the average frame looks fine, but three of five frames are late, each for a different reason (a GC collection, a script spike, a physics spike). Players feel spikes as stutter. Always look at the worst frames, not just the average FPS.

Draw calls and batching

The CPU has to tell the GPU about every mesh, material and state change. Fewer, cheaper draw calls and SetPass calls (shader/material changes) mean less CPU time spent on rendering. URP's tools:

Technique What it does Requirements
SRP Batcher makes draw calls with the same shader cheap by keeping material data on the GPU URP default; compatible shaders (URP Lit, Shader Graph); no MaterialPropertyBlock
GPU instancing draws many copies of one mesh + material in one call Enable GPU Instancing on the material; used when the SRP Batcher doesn't apply
GPU Resident Drawer (Unity 6) submits static and dynamic meshes via BatchRendererGroup, cutting CPU cost for large scenes enable in the URP asset; needs the Forward+ path and compute support
Static batching combines static meshes at build time mark objects Batching Static; costs memory
Fewer materials texture atlases, shared materials art pipeline discipline

Open the Frame Debugger, step through the draws, and read each batch's "why this draw call can't be batched with the previous one" note (different material, different shader keywords, a property block...). Also check the Rendering profiler module for batch and SetPass counts.

Test yourself

Why profile a development build on the target device rather than in the editor?

  1. The editor has no profiler
  2. The editor adds its own overhead and runs on different hardware
  3. Builds are faster to make
  4. The editor hides GC

What does a ProfilerMarker give you?

  1. Automatic optimization
  2. A named, low-cost timing section in the Profiler hierarchy
  3. A breakpoint
  4. A log message per frame

Which change makes a URP renderer incompatible with the SRP Batcher?

  1. Using URP Lit
  2. Setting properties through a MaterialPropertyBlock
  3. Using Shader Graph
  4. Marking it static