An enemy disappears, but the next enemy still needs fresh heap space. In Unity, destroying a GameObject does not make its memory immediately reusable: the garbage collector (GC) reclaims unused memory later. If collection runs during a boss fight, its CPU work can cause an unexpected frame-rate drop. section 3.2.1 section 3.2
Listing 3.2 Garbage collection example.
GameObject enemy1 = Instantiate(enemyPrefab); GameObject.Destroy(enemy1); GameObject enemy2 = Instantiate(enemyPrefab);
Destroying the first enemy does not guarantee that the second can reuse its memory. Repeatedly creating and destroying enemies can therefore increase heap use while collection is pending. section 3.2.1
C# manages heap memory automatically. The GC finds objects no longer in use, marks them for removal, and reclaims their memory in collection passes. That convenience has costs: reclamation is delayed, collection consumes CPU time, and Unity’s non-compacting GC does not close gaps left in memory. Scattered GameObjects can also mean more cache misses. section 3.2 section 3.2.1
Listing 3.3 Allocating 100 temporary arrays per frame
private void Update()
{
for (int i = 0; i < 100; i++)
{
byte[] array = new byte[1000];
array = null;
}
}This Update loop creates 100 temporary 1,000-byte arrays each frame and drops their references. The Unity Profiler reports about 100 KB of GC allocation for the frame—not immediate reuse of each array’s space. section 3.2.1
Reduce collection pressure rather than relying on timely collection:
- Allocate related data when loading a game or level, keep it for a shared lifetime, and release it together or in reverse order when possible. section 3.2.4 section 3.6
- Use stack allocations for temporary data and object pools to recycle frequently needed objects instead of repeatedly instantiating and destroying them. section 3.2.4 section 3.3.1
- If collection is unavoidable, consider System.GC.Collect() at a loading screen or menu transition, when a pause affects the player less; do not use it as a routine gameplay fix. section 3.2.4 section 3.2.1











