In a Unity survival game, repeatedly instantiating enemies and destroying them after they are shot can leave gaps in heap memory. Those gaps matter when a later allocation needs one contiguous chunk, not merely enough free memory in total. section 3.3 section 3.3.1 section 3.1
Enough free memory, but no room
Allocate arrays of 1 KB, 2 KB, and 1 KB, then remove the first and third. The two resulting holes total 2 KB, but each holds only 1 KB. A new 1.5 KB array cannot fit in either hole. section 3.1
Figure 3.4 We have 2048 bytes of memory free, but if we try to allocate an array of 1536 bytes, we’ll run out of memory because the biggest contiguous space is 1024 bytes.

The diagram contrasts total free space with the largest contiguous hole—the limit that determines whether the new array fits. section 3.1
Heap objects can leave separated holes when they are released in a different order from their allocation. Stack data avoids this pattern by being released in reverse order. Unity adds a constraint: destroying a GameObject does not make its memory immediately reusable, and its garbage collector does not compact the remaining objects to close gaps. section 3.1 section 3.3.1 section 3.2
Reduce the churn that creates holes:
- Keep related heap data with the same lifetime together; release it together or in reverse order where possible. section 3.1
- For frequently spawned enemies, reuse GameObjects from an object pool rather than repeatedly instantiating and destroying them. section 3.3.1 section 3.6
- Allocate common data when the game loads and level-specific data when the level loads; avoid routine allocation and deallocation during gameplay. section 3.6


