Contact

Type to explore Drawk studio productions

Discover cross-platform games, mobile apps, architecture articles, and interactive GLSL labs.

← Back to Posts

Incremental Garbage Collection in Unity: Safe Points, Pool Trimming, and Smooth Frame Times

TL;DR: Zero-allocation hot paths are always rule one, yet real Unity projects still allocate across scene loads, audio downloads, UI screens, and third-party SDKs. In Action Bots and our shared studio engine layer, we eliminated mid-round GC freezes by turning on gcIncremental, replacing every blocking GC.Collect() with a centralized MemoryUtil service, slicing runtime collections to 1.5 - 3 ms per frame, trimming pooled GameObjects before Resources.UnloadUnusedAssets(), and reserving full sweeps for settled Safe Points.

Incremental Garbage Collection in Unity: Slice GC work into 2 ms frames and defer full sweeps to safe points.

In Part 1 of this series, we focused on keeping hot gameplay loops allocation-free. That stops the steady trickle of per-frame garbage.

But real shipped games also stream audio clips, instantiate and retire levels, open and close UI screens, and integrate third-party mobile SDKs. When managed memory eventually needs reclaiming, a single blocking GC.Collect() or synchronous Resources.UnloadUnusedAssets() call can freeze the main thread for 30 to 60 milliseconds right in the middle of combat.

This post walks through the exact Incremental GC + Safe-Point architecture we integrated into Action Bots and our shared Unity engine libraries (MemoryUtil, ObjectPool.trim, BaseGameController, BaseUIController, and UIPanelBase), along with the real profiler lessons and edge cases we hit along the way.

flowchart TD subgraph GAMEPLAY["LIVE GAMEPLAY (busy = true)"] G1["RequestCollect / Audio / Wave End"] --> G2["pendingIncremental = true (NEVER blocks)"] G3["Heap sampled every 30 frames"] -->|"+4MB to +16MB growth"| G2 G2 --> G4["GarbageCollector.CollectIncremental(1.5ms - 3ms)"] G4 -->|"More work"| G4 G4 -->|"Cycle finished"| G5["Reset heap baseline"] end subgraph SAFEPOINT["SAFE POINTS (busy = false, or Low Memory)"] S1["Level Prepare / Scene Load / Results / Pause / App Background"] --> S2["Wait real-time tween settle (0.6s, unscaled)"] S2 --> S3["1. Trim object pools oldest-first (keep 4-16) + onSafePointReclaim"] S3 --> S4["2. GC.Collect() frees dropped wrappers"] S4 --> S5["3. yield return Resources.UnloadUnusedAssets()"] S5 --> S6["4. Sweep & update cooldown + baseline"] end GAMEPLAY -. "Round ends (busy -> false)" .-> SAFEPOINT
┌────────────────────────────────────────────────────────────────────────────┐
│            SAFE-POINT RECLAIM ORDER (WHY SEQUENCE MATTERS)                 │
├────────────────────────────────────────────────────────────────────────────┤
│  1. Release References First  -> ObjectPool.trim(keep) + UI view reclaim   │
│                                  (destroys surplus pooled GameObjects)     │
│  2. Managed GC Sweep          -> GC.Collect() frees managed wrappers       │
│                                  pointing at those meshes & materials      │
│  3. Native Asset Unload       -> yield return Resources.UnloadUnusedAssets │
│                                  (now actually sees assets as unreferenced)│
│  4. Final Sweep & Cooldown    -> GC.Collect() + reset heap baseline        │
└────────────────────────────────────────────────────────────────────────────┘

1. Enabling Incremental GC (And the Editor Restart Trap)

Unity's Boehm-Demers-Weiser garbage collector supports incremental marking when Use Incremental GC is enabled under Edit > Project Settings > Player > Other Settings > Configuration (gcIncremental: 1 in ProjectSettings/ProjectSettings.asset, or PlayerSettings.gcIncremental = true).

Before writing any code around it, check two runtime truths that catch teams off guard:

  1. The runtime reads gcIncremental only at VM startup. If you flip PlayerSettings.gcIncremental = true in an already-open Unity Editor session, GarbageCollector.isIncremental stays false until you fully restart the Editor. Player builds pick it up from launch, and the Editor may have incremental GC off by default. Always inspect GarbageCollector.isIncremental at runtime before judging slice behavior.
  2. Another system can disable collection via GarbageCollector.GCMode. Always gate incremental work on both flags:
using UnityEngine.Scripting;

public static bool isIncrementalAvailable {
    get {
        return GarbageCollector.isIncremental
            && GarbageCollector.GCMode == GarbageCollector.Mode.Enabled;
    }
}

At startup, we also override Unity's default 3 ms slice budget (3_000_000 ns) down to 1.5 - 2.0 ms on low- and mid-tier hardware so a 60 FPS (16.6 ms) or 120 FPS (8.3 ms) frame keeps enough headroom for physics and rendering. A cycle simply spans a couple of extra frames without spiking frame time.


2. Understanding CollectIncremental Return Semantics (And When Not to Force Cycles)

When driving incremental slices manually from Update(), Unity's GarbageCollector.CollectIncremental(ulong nanoseconds) has two subtle behaviors:

  • Return value meaning: CollectIncremental returns true while marking work still remains in the current cycle, and false when the cycle finishes OR when incremental GC is unavailable. If you write a fallback path without checking GarbageCollector.isIncremental first, false looks like "finished" and your fallback silently skips collecting.
  • Avoid blind fixed-timer calls: Calling CollectIncremental starts a new collection cycle whenever none is active. With gcIncremental: 1 enabled, Unity already schedules incremental slices automatically when heap allocations reach the runtime's threshold. Calling CollectIncremental on a fixed 30-second timer regardless of actual heap growth creates extra marking CPU work even on idle frames.

Instead, in MemoryUtil.Update(), we sample GC.GetTotalMemory(false) every 30 frames (heapSampleFrameInterval) and only kick off an explicit incremental cycle when heap growth exceeds a tier-tuned threshold (heapGrowthTriggerBytes, such as 4 - 16 MB), or when a caller calls MemoryUtil.RequestCollect(reason) during gameplay:

private void Update() {

    if (!isIncrementalAvailable) {
        return;
    }

    // Sample the heap occasionally rather than every frame, and start a cycle on
    // growth alone so a long round does not rely on somebody remembering to ask.
    if (!pendingIncremental
        && (Time.frameCount % heapSampleFrameInterval) == 0) {

        long total = GC.GetTotalMemory(false);

        if (total - heapBaselineBytes > heapGrowthTriggerBytes) {
            pendingIncremental = true;
        }
    }

    if (!pendingIncremental) {
        return;
    }

    // CollectIncremental returns true while there is still work left in the cycle.
    // Each call is bounded by the slice, so per-frame cost stays predictable.
    bool moreWork = GarbageCollector.CollectIncremental(SliceNanoseconds());

    if (!moreWork) {
        pendingIncremental = false;
        incrementalCycles++;
        heapBaselineBytes = GC.GetTotalMemory(false);
    }
}

If you run periodic incremental slices on a map or hub world where heavy transitions, raids, or fast scrolling happen, consider gating the batch with an active-visibility + player-idle predicate so a 2 ms slice batch does not stack onto a frame that is already busy animating or scrolling.


3. Replacing Direct GC.Collect() Calls with MemoryUtil

When we audited Action Bots for mid-round hitches, gcIncremental was off (0) and six runtime call sites were invoking blocking GC.Collect() directly (a HUD coroutine when vehicle audio started, an audio clip downloader, and audio recorder clip loads), alongside commented-out Resources.UnloadUnusedAssets() calls that the original authors had disabled because inline unloads froze the screen.

We replaced all six with one shared singleton service (MemoryUtil, living on a persistent DontDestroyOnLoad object) exposing a strict contract:

  • MemoryUtil.SetBusy(bool) - The gameplay layer reports when frame spikes would be felt. While busy is true, nothing blocks.
  • MemoryUtil.RequestCollect(reason) - Safe anywhere (wave end, clip load, panel teardown). Sets pendingIncremental = true, and if busy is true or the cooldown has not elapsed, stops there without blocking.
  • MemoryUtil.RequestUnloadUnusedAssets(reason) - Always deferred to a safe point.
  • MemoryUtil.CollectAtSafePoint(reason, force, delaySeconds) - Schedules the full pool-trim + collect + unload sequence for a loading screen, results screen, or UI transition.
  • MemoryUtil.CollectBlocking(reason) - Explicit escape hatch for loading screens; logs a warning if accidentally called while busy.

The SetBusy State-Edge Trap We Caught in Live Testing

Our first wiring pushed MemoryUtil.SetBusy(...) inside BaseGameController.changeGameState(...). In live round profiling, we caught a surprise: busy was false during gameplay and twelve full collects still ran mid-round!

The reason was an assumption about the state enum. In that codebase, gameState was already GameStateGlobal.GameStarted at the main menu and did not transition when a round started - so busy went true once at boot, false at the first GameResults, and never turned back on.

The fix was pushing MemoryUtil.SetBusy(GameConfigs.isGameRunning) in BaseGameController.Update() above the if (!GameConfigs.isGameRunning) return; early-return:

// Placed ABOVE the !isGameRunning early-return so the false edge when a round
// ends is still seen. SetBusy early-returns when unchanged (one bool compare/frame).
MemoryUtil.SetBusy(GameConfigs.isGameRunning);

if (!GameConfigs.isGameRunning) {
    return;
}

Leaving gameplay (SetBusy(false)) automatically flushes any safe-point work queued during the round:

public static void SetBusy(bool value) {

    if (busy == value) {
        return;
    }

    busy = value;
    Init();

    MemoryUtil driver = Instance;

    // Leaving gameplay IS a safe point. Anything requested during the round
    // gets serviced now, on the transition, where the frame cost is hidden.
    if (!busy && driver != null
        && (pendingSafePointCollect || pendingSafePointUnload)) {

        driver.RunSafePoint("busy-cleared");
    }
}

After that one-line fix, live-round telemetry confirmed the exact behavior across a full 90-second round:

Metric During Live Round (busy = true) On Round End (busy -> false)
fullCollects Frozen at 4 4 -> 6
incrementalCycles 7 -> 13 (slices only) 15
unloads Frozen at 2 2 -> 3

4. Wiring Every Safe Point (And Avoiding Transition Stutters)

In Action Bots, safe-point collection is wired to six natural boundaries:

Boundary Call Notes
Level Prepare MemoryUtil.CollectAtSafePoint("level-prepare-" + levelCode, true) Called in prepareGame() before loadLevelAssets() with force: true so the outgoing level is freed before the next level lands in RAM.
UI Screen Changes MemoryUtil.CollectAtSafePoint("ui-show", false, MemoryUtil.uiTransitionSettleSeconds) Cooldown-guarded + delayed by 0.6 s real time so the menu animate-in finishes before the sweep.
Single-Scene Loads SceneManager.sceneLoaded (only when mode == LoadSceneMode.Single) Ignores LoadSceneMode.Additive, which adds content mid-gameplay rather than unloading a previous scene.
Round End / Quit SetBusy(false) and changeGameState (GameResults / GameQuit) Flushes deferred requests behind the results or quit transition.
App Backgrounded OnApplicationPause(true) Free safe point on mobile: nothing renders, and the OS is deciding right then whether to keep the process alive.
OS Low Memory Application.lowMemory The one override that ignores both busy and fullCollectCooldownSeconds. Being killed by the OS costs more than a dropped frame.

Notice two timing details in the safe-point coroutine below:

  1. Always yield return null; on line 1 of the coroutine. In Unity, StartCoroutine(...) executes everything before the first yield synchronously on the caller's frame. Starting with yield return null; ensures the frame that requested cleanup finishes cleanly first.
  2. Use Time.realtimeSinceStartup for settle delays, never Time.time or WaitForSeconds. Pause and menu screens routinely run with Time.timeScale = 0, where scaled timers hang forever. And if busy flips back to true during the settle delay (the player jumped right back into gameplay), abort the safe point and leave the pending flags intact for the next exit!
private IEnumerator SafePointCo(string reason) {

    // Let the caller's frame finish before touching memory.
    yield return null;

    // Wait in REAL time for any incoming screen tween to settle.
    float delay = pendingSafePointDelay;
    pendingSafePointDelay = 0f;

    if (delay > 0f) {
        float until = Time.realtimeSinceStartup + delay;

        while (Time.realtimeSinceStartup < until) {
            if (busy) {
                safePointRunning = false;
                yield break;
            }
            yield return null;
        }
    }

    bool doUnload = pendingSafePointUnload;
    bool doCollect = pendingSafePointCollect;
    pendingSafePointUnload = false;
    pendingSafePointCollect = false;

    // 1. Release references FIRST (pool trim + cache/view reclaim).
    int trimmed = ReclaimReferences(reason);

    // 2. Collect managed wrappers so native asset references are dead.
    if (doCollect) {
        GC.Collect();
        fullCollects++;
    }

    // 3. Asynchronously unload unreferenced textures, meshes, and audio.
    if (doUnload) {
        AsyncOperation op = Resources.UnloadUnusedAssets();
        while (op != null && !op.isDone) {
            yield return null;
        }
        unloads++;

        // 4. Sweep what the unload just released.
        GC.Collect();
        fullCollects++;
    }

    lastFullCollectTime = Time.realtimeSinceStartup;
    heapBaselineBytes = GC.GetTotalMemory(false);
    pendingIncremental = false;
    safePointRunning = false;

    // Drain any new requests that arrived while UnloadUnusedAssets spanned frames.
    if (!busy && (pendingSafePointCollect || pendingSafePointUnload)) {
        RunSafePoint(reason + "+queued");
    }
}

One Exception Worth Keeping Blocking: Scene Pops

When popping a full-screen modal scene back to a world scene behind a transition fade, keeping a single blocking GC.Collect() inside the pop transition is often better than slicing it incrementally. A pop is one-shot (not a loop), the hitch is already masked by the transition, and slicing it pushes GC marking into the first frames of the incoming scene while it initializes.


5. Pool Trimming and UI View Reclaim Before Unloading Assets

One of the biggest misconceptions in Unity memory management is calling Resources.UnloadUnusedAssets() while object pools and hidden UI panels still hold references to the previous level's meshes, materials, and textures. UnloadUnusedAssets() frees zero assets that are still referenced by parked pooled objects.

ObjectPool.trim(int keep)

In our shared engine ObjectPool, clear() used to destroy every parked object (forcing expensive Instantiate spikes on the next spawn), while normal pooling never shrank after a heavy battle. We added trim(int keep) to dequeue and destroy surplus parked instances oldest-first while preserving a warm baseline:

/// <summary>
/// Release cached objects beyond <paramref name="keep"/>, oldest first, and return
/// how many were destroyed. Only touches objects sitting in the queue -- anything
/// live in the world was never enqueued and cannot be taken from its owner.
/// </summary>
public int trim(int keep) {

    if (keep < 0) {
        keep = 0;
    }

    int destroyed = 0;

    while (pool.Count > keep) {

        GameObject go = pool.Dequeue();
        pooledSet.Remove(go);

        if (go != null) {
            go.DestroyNow();
            destroyed++;
        }
    }

    return destroyed;
}

In Play Mode verification, spawning and recycling 60 projectile instances and hitting one forced safe point produced cached=16, trimmed=44, freeing 44 stale prefab trees right before GC.Collect() and UnloadUnusedAssets().

Hidden UI Toolkit Views (isVisible vs. activeInHierarchy)

In UIPanelBase, we also uncovered a subtle UI Toolkit leak when subscribing to MemoryUtil.onSafePointReclaim:

  • Hook in AfterSceneLoad, not BeforeSceneLoad: MemoryUtil resets its statics (including onSafePointReclaim = null) in [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] so fast Play Mode runs without domain reload never carry stale state. Because two BeforeSceneLoad methods have undefined execution order, UI subscribers must register in AfterSceneLoad.
  • Check isVisible, not activeInHierarchy: Pooled UI panels stay activeInHierarchy == true while hidden (7 of 7 hidden panels measured isVisible == false with activeInHierarchy == true after returning to the menu), still holding their VisualTreeAsset / PanelRenderer trees in memory.
  • Only drop hidden views on "low-memory" or "application-paused": Sweeping views on every menu transition would tear down panel-main, panel-header, and panel-footer right before the user navigates back to them.
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
private static void HookSafePointReclaim() {

    viewsReclaimed = 0;
    lastViewReclaim = "";

    MemoryUtil.onSafePointReclaim -= OnSafePointReclaim;
    MemoryUtil.onSafePointReclaim += OnSafePointReclaim;
}

private static void OnSafePointReclaim(string reason) {

    // Only drop hidden UI views when the OS asks for memory or backgrounds the app.
    if (reason != "low-memory" && reason != "application-paused") {
        return;
    }

    UIPanelBase[] panels = UnityEngine.Object.FindObjectsByType<UIPanelBase>(
        FindObjectsInactive.Include, FindObjectsSortMode.None);

    for (int i = 0; i < panels.Length; i++) {
        UIPanelBase panel = panels[i];
        if (panel == null || panel.isVisible || !panel.isToolkitPanel) {
            continue;
        }
        panel.FreeToolkitView();
    }
}

6. Device Tiering: Collect Sooner on Low-End Phones

One size does not fit a 2 GB phone and a 32 GB desktop. In MemoryUtil.TuneForDevice(), we inspect SystemInfo.systemMemorySize and SystemInfo.processorCount once in Awake() and auto-tune four knobs. A low-end device collects sooner and more often in smaller bites, because a smaller heap trigger keeps each incremental marking pass short:

if (memoryMB > 0 && (memoryMB < 3072 || cores <= 4)) {
    deviceTier = DeviceTier.Low;
    heapGrowthTriggerBytes = 4 * 1024 * 1024;
    sliceMilliseconds = 1.5f;
    fullCollectCooldownSeconds = 8f;
    poolKeepPerBucket = 4;
}
else if (memoryMB > 0 && memoryMB < 6144) {
    deviceTier = DeviceTier.Medium;
    heapGrowthTriggerBytes = 8 * 1024 * 1024;
    sliceMilliseconds = 2f;
    fullCollectCooldownSeconds = 15f;
    poolKeepPerBucket = 8;
}
else {
    deviceTier = DeviceTier.High;
    heapGrowthTriggerBytes = 16 * 1024 * 1024;
    sliceMilliseconds = 3f;
    fullCollectCooldownSeconds = 30f;
    poolKeepPerBucket = 16;
}

7. Why Incremental GC Still Needs Clean Hot Paths (Real Profiler Proof)

Even with Incremental GC and MemoryUtil live, one single per-frame bug can overwhelm a 2 ms slice budget. During a follow-up profiler capture in Action Bots, a worst frame hit 154 ms with GC.Collect at 58.68 ms plus GarbageCollector.CollectIncremental at 12.19 ms.

Walking every GC.Alloc sample up to its nearest managed caller revealed the true culprit wasn't bullets or physics at all: 87% of all gameplay allocation (36,201 KB over 301 frames) came from StackTraceUtility.ExtractStringFromExceptionInternal caused by a single unguarded NullReferenceException firing on every input-axis broadcast (438 exceptions per frame), followed by Animation[string] wrapper allocations and uncached audio/pool-key lookups.

Fixing those hot-path allocations cut gameplay allocation by 81% (141,511 B/frame down to 26,717 B/frame), starving the GC spikes of fuel while MemoryUtil + gcIncremental smoothly handled the remaining background asset churn. When heavy simulation or world math grows beyond what managed C# should touch per frame, pair this setup with data-oriented ECS buffers or a native C++ core behind a C ABI (our multi-engine architecture pattern), and verify real GC.Alloc call stacks with automated profiler checks (see our Unity CLI profiling add-on notes).

References, Standards & Verified Data


Revision History

  • 2026-12-03 (Revision 1 - Initial Release):
    • Sections Modified: Initial publication.
    • Summary: Published dedicated Part 2 deep dive covering Incremental GC configuration, MemoryUtil busy-guard and safe-point implementation, ObjectPool.trim(keep) pool trimming, UIPanelBase view reclaim, device tiering, and live profiler verification results from Action Bots.

← Back to All Posts