Runtime Engineering / Memory / GC

Unity GC Spikes and Memory Profiling Guide

A frame hitch after firing, opening a menu or loading a scene may be allocation-related, but the label 'memory leak' is often applied too early. Separate transient managed allocations, retained objects and native memory growth.

Fyros Games Studio technical field guide | Updated October 2026 | For Unity production teams

Fast answer: Use a player-build CPU profile to locate GC.Alloc spikes, capture call stacks for the allocation site, then compare Memory Profiler snapshots during a controlled session to establish whether live memory is actually retained. Fix the generating code before treating GC mode as the main solution.

1. Distinguish three different memory problems

Memory issues present similarly to players but require different repairs. A collection spike may pause gameplay even if total resident memory stays stable. A slowly growing live object graph may indicate retained references. Native GPU allocations can grow without appearing as a matching managed heap increase.

SymptomWhat it can meanBest first tool
Short hitch with GC.CollectManaged allocations increase collection pressureCPU Usage and GC.Alloc call stacks
Memory keeps increasing after repeated gameplayObjects may remain referenced or pools may expandMemory Profiler snapshots and retained object graphs
Crash near platform memory limitTextures, meshes, render textures, audio or other native resourcesMemory Profiler plus platform memory tooling
First open of inventory hitchesOne-time UI allocation, asset load or shader initializationControlled first versus second interaction captures
Periodic hitch without visible GCPhysics, render work, streaming or sync costCPU timeline and GPU counters

The managed heap, native allocations and graphics memory are related but not interchangeable. A lower GC.Alloc value does not prove total memory dropped, and a large heap does not alone establish a leak.

2. Find the allocation site rather than guessing

  1. Reproduce the hitch in a development player on the affected device or a representative build; capture the exact moment.
  2. In the CPU Usage Profiler, inspect GC.Alloc on slow frames and expand the hierarchy into call stacks where supported.
  3. Separate allocations made every frame from occasional setup costs. Repeated hot-path allocations usually deserve earlier attention.
  4. Annotate the gameplay action that triggers each allocation, such as opening inventory, updating a scoreboard or spawning a bullet.
  5. Investigate the actual caller before changing global GC behavior. An apparent allocation in a UI system may be caused by upstream data formatting.
  6. After a candidate fix, capture the same action again and compare allocations and frame-time percentiles.

Do not profile only inside the Editor when making final claims. Editor-only instrumentation and behavior can produce different allocation measurements from a shipped player. Unity recommends gathering accurate data on the target platform.

A 0 B GC.Alloc marker during one gameplay segment is useful but does not establish zero allocation across a full game. Include transitions, network events, UI and rare abilities in the capture plan.

3. Common allocation sources in Unity gameplay

Per-frame strings and labels

Repeated ToString calls, string interpolation and formatted debug output can allocate when performed continuously. Cache results or update UI only when values change.

LINQ and temporary collections

Queries inside Update, inventory sorting and combat scans can produce iterators or temporary arrays. Validate with the profiler before rewriting readable code.

Instantiate and Destroy loops

Short-lived projectiles, hit effects and spawned UI rows can create allocation and initialization pressure. Test pooling for measured hot paths.

Delegates and closures

Capturing lambdas inside frequently executed operations may allocate. Inspect the exact call site and avoid premature broad refactors.

Boxing and API return values

Value types used through object-based APIs may allocate. Profiling and call stacks are more reliable than coding folklore.

Third-party systems

Middleware, analytics callbacks, serialization and networking packages can allocate outside the gameplay script that first appears suspicious.

Object pooling is not always better. Oversized pools keep memory alive, can increase baseline usage and may hide lifetime bugs. Pool only objects whose creation cost is proven significant, cap the pool and measure retained memory.

4. Use memory snapshots to test a leak hypothesis

Take snapshots at defined checkpoints rather than choosing arbitrary moments. For example, start a clean level, play three identical encounters, return to menu, allow expected cleanup, and compare against the first snapshot. Repeat on the same platform with a known initialization order.

  1. Snapshot A: stable menu or level start after expected assets have loaded.
  2. Snapshot B: after one repeatable combat sequence or scene transition.
  3. Snapshot C: after multiple equivalent cycles and expected cleanup.
  4. Compare managed objects, native assets, texture sizes and reference paths. Identify categories that grow between snapshots.
  5. Inspect whether referenced objects are legitimately cached, pooled or retained by a manager. Growth alone is not proof of a leak.
  6. Remove one retention cause at a time, replay the sequence and compare new snapshots.

Be careful when comparing snapshots captured at different times in streaming scenes. Assets may still be loading, released resources may not yet be reclaimed, and intentionally cached data may remain for reuse. The reproducible sequence matters as much as the absolute number.

5. Understand incremental garbage collection

Unity supports incremental garbage collection on supported platforms. Instead of completing a full collection in one interruption, it can spread work over multiple frames and reduce the visible size of individual GC pauses. That does not make unnecessary allocations free, and it does not reduce all sources of memory pressure.

Incremental collection also carries bookkeeping overhead. Under some heavy mutation patterns it can fall back to a full collection. Verify the settings in the project's Unity version and measure both normal play and stress cases after changing them.

The robust order is: reduce unnecessary allocations, confirm object lifetimes, test collection behavior on the build, and only then decide whether more invasive architecture work is needed.

6. A scoped example: scoreboard stutter

Suppose a sports game stutters whenever a large player stats panel opens. The first hypothesis might be that the UI needs fewer graphics. But a CPU capture could reveal repeated allocation while formatting dozens of player lines, rebuilding layout and recreating icons. The renderer may not be the primary cost.

A sensible experiment caches reusable elements, batches data updates and changes only those values that actually changed. It then measures panel-open time, total allocation and the visible result. If the first open still hitches, investigate sprite, font and asset initialization separately.

This is an illustrative debugging scenario, not a claim that any specific Fyros client project had that fault or achieved a given benchmark.

7. Evidence checklist for a production memory review

ArtifactMinimum useful detail
ReproductionExact scene, action sequence and number of repetitions
Build metadataUnity version, scripting backend, platform, build configuration
Profiler captureSlow frame with GC.Alloc and relevant call stacks
Memory snapshotsRepeatable A/B/C checkpoints with retained objects
BudgetDevice memory constraints and acceptable peak
Acceptance criteriaNo uncontrolled growth after cycles; frame pacing maintained

When deciding whether to bring in outside engineering help, the best first milestone is often a constrained audit with ranked fixes. A report that identifies a retained reference and a measurable allocation source is more actionable than a generic recommendation to use object pooling everywhere.

GC spikes or memory growth delaying your game?

Fyros can scope investigation and fixes across scripting allocations, UI, asset loading, memory retention and performance regressions in an existing Unity project.

DISCUSS YOUR UNITY PROJECT

Send the Unity version, build platform, current performance numbers, a reproducible scene and your release target. No unsupported promises or guaranteed FPS numbers.

Common questions

Is a GC spike the same as a memory leak?

No. A GC spike is collection activity that can interrupt a frame. A leak or unintended retention means memory remains referenced or unreleased across time. They require different evidence.

Does enabling incremental GC eliminate Unity stutters?

No. It can distribute some collection work across frames. It cannot remove the allocations causing pressure or solve native memory growth.

Why does the Unity Memory Profiler show growth after loading a level?

Loading intentionally creates objects and caches. Compare controlled snapshots after expected cleanup and inspect reference ownership before classifying growth as a leak.

Can Fyros review memory and GC problems in an existing Unity build?

Yes, a scoped review can be discussed through Hire Us. Include a player build, target device, repeatable hitch and any profiler or snapshot captures available.

Technical references

These are upstream Unity references for platform- and version-specific verification. They are not evidence that any particular project achieved a specific result.