# Object Pooling

## Object Pooling Overview

The **Runtime Spawner** uses an integrated object pooling system to ensure spawning and despawning are **fast, deterministic, and GC-free** — even in large-scale encounters or multiplayer environments.

Pooling eliminates the performance overhead of frequent `Instantiate()` and `Destroy()` calls, which are some of the most expensive operations in Unity.

***

### 1. What Is Object Pooling?

Normally, to add an object into a scene, you call:

```csharp
Instantiate(enemyPrefab, position, rotation);
```

While simple, this operation allocates new memory, builds components, and triggers Awake/Start calls — all of which can cause **frame-time spikes** when done frequently.

Pooling solves this by **reusing existing instances** instead of creating new ones.

#### Basic Pooling Concept

| Action      | Built-in        | With Pool        |
| ----------- | --------------- | ---------------- |
| Spawn       | Instantiate()   | Get() from pool  |
| Despawn     | Destroy()       | Return() to pool |
| Performance | Expensive       | Constant-time    |
| Memory      | Frequent allocs | Stable footprint |

When the level starts, a pool **pre-spawns** objects. During gameplay, the spawner simply borrows from that pool, and when an object is no longer needed, it’s returned and disabled.

***

### 2. Why It Matters

* **Stable Framerate:** No runtime spikes when enemies, projectiles, or FX appear.
* **Lower GC Pressure:** Prevents allocation churn and temporary garbage.
* **Scalable:** Enables hundreds or thousands of active entities without bottlenecks.
* **Network Ready:** Syncs cleanly when paired with pooled network systems like Photon Fusion or PUN.

> The Runtime Spawner automatically handles pooling internally —\
> you do *not* need to write custom pooling code unless you want to.

***

### 3. The Megacrush Object Pool Package

Runtime Spawner uses the [**Megacrush Object Pool**](https://www.megacrush.app/api/object-pool) package under the hood.

Key features:

* Zero-GC allocation model.
* Configurable prewarm counts and limits.
* Thread-safe handle lifecycle.
* Built-in adapters for local and networked modes.

You can use it independently or extend it with your own adapter for specialized behaviors.

***

### Next Steps

* Spawner Pool Integration — how the Runtime Spawner automatically manages pooling through factories and providers.
* Custom Pooling Systems — how to plug in your own pooling backend.
