In this lesson, you will learn how to reduce garbage collection spikes and improve performance by reusing "dead" actors instead of constantly destroying and spawning them.
The Problem with Frequent Spawning
When you create a fast-paced game—like a shooter—you might spawn dozens of projectiles every second. Calling SpawnActor and DestroyActor repeatedly is expensive. It forces Unreal Engine to allocate memory, initialize components, and eventually trigger the Garbage Collector (GC) to clean up the orphaned memory. This constant cycle leads to "hiccups" or frame-rate stutters during intense gameplay.
The Solution: Actor Pooling
Actor Pooling treats your actors like a library collection. Instead of throwing a book away when you’re done reading, you place it back on a shelf so the next person can borrow it.
- Initialization: At the start of the level, create a
TArrayorTQueueof actors (the "pool"). - Borrowing: When you need a projectile, don’t spawn a new one. Pull an inactive actor from the pool, move it to the firing location, and "activate" it.
- Returning: When the projectile hits a wall or expires, don’t destroy it. Instead, hide it, disable its collision, deactivate its movement, and return it to the pool for future use.
Basic Implementation Logic
You can manage this using an Actor Component that keeps track of your pool:
// In your Pool Manager
AActor* GetFromPool() {
if (InactiveActors.Num() > 0) {
AActor* PooledActor = InactiveActors.Pop();
PooledActor->SetActorHiddenInGame(false);
PooledActor->SetActorEnableCollision(true);
return PooledActor;
}
return GetWorld()->SpawnActor<AActor>(ActorClass); // Fallback
}
By hiding the actor and toggling its physics/collision, you bypass the heavy memory allocation process. This keeps your memory footprint stable, as you aren't constantly creating new objects, which keeps the Garbage Collector quiet and your frame rate smooth.
Key Takeaway: Instead of destroying actors and triggering garbage collection, keep a "pool" of inactive actors that you reset and recycle to maintain consistent frame performance.