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.
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.
| Symptom | What it can mean | Best first tool |
|---|---|---|
| Short hitch with GC.Collect | Managed allocations increase collection pressure | CPU Usage and GC.Alloc call stacks |
| Memory keeps increasing after repeated gameplay | Objects may remain referenced or pools may expand | Memory Profiler snapshots and retained object graphs |
| Crash near platform memory limit | Textures, meshes, render textures, audio or other native resources | Memory Profiler plus platform memory tooling |
| First open of inventory hitches | One-time UI allocation, asset load or shader initialization | Controlled first versus second interaction captures |
| Periodic hitch without visible GC | Physics, render work, streaming or sync cost | CPU 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
- Reproduce the hitch in a development player on the affected device or a representative build; capture the exact moment.
- In the CPU Usage Profiler, inspect GC.Alloc on slow frames and expand the hierarchy into call stacks where supported.
- Separate allocations made every frame from occasional setup costs. Repeated hot-path allocations usually deserve earlier attention.
- Annotate the gameplay action that triggers each allocation, such as opening inventory, updating a scoreboard or spawning a bullet.
- Investigate the actual caller before changing global GC behavior. An apparent allocation in a UI system may be caused by upstream data formatting.
- 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.
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.
- Snapshot A: stable menu or level start after expected assets have loaded.
- Snapshot B: after one repeatable combat sequence or scene transition.
- Snapshot C: after multiple equivalent cycles and expected cleanup.
- Compare managed objects, native assets, texture sizes and reference paths. Identify categories that grow between snapshots.
- Inspect whether referenced objects are legitimately cached, pooled or retained by a manager. Growth alone is not proof of a leak.
- 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
| Artifact | Minimum useful detail |
|---|---|
| Reproduction | Exact scene, action sequence and number of repetitions |
| Build metadata | Unity version, scripting backend, platform, build configuration |
| Profiler capture | Slow frame with GC.Alloc and relevant call stacks |
| Memory snapshots | Repeatable A/B/C checkpoints with retained objects |
| Budget | Device memory constraints and acceptable peak |
| Acceptance criteria | No 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 PROJECTSend 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.