Object pooling
- Game Development course
- Expert
- Lesson 3/47
- 4 min
Learn to avoid repeated Instantiate with object pooling.
Object pooling and the GC problem
Using Instantiate and Destroy frequently to spawn and remove bullets, particles, or enemies kills performance. It continuously allocates memory, triggering the Garbage Collector (GC) and causing noticeable frame stutters.
// BAD: Memory allocation every shot followed by GC
Instantiate(mermiPrefab, pos, rot);
Destroy(mermi, 2.0f);The solution is to deactivate objects instead of destroying them, reusing them as needed.
Managing the pool queue
A pool is usually managed with a Queue<GameObject> collection. At startup, objects are instantiated and hidden with SetActive(false). When needed, an object is popped (Dequeue) and activated; when done, it is returned (Enqueue) back to the pool.
Queue<GameObject> pool = new Queue<GameObject>();
GameObject GetObject() {
GameObject obj = pool.Dequeue();
obj.SetActive(true);
return obj;
}This delivers smooth gameplay with zero runtime memory allocations.
Practice Take object from pool and print status
Retrieve the first bullet from the queue (pool) using Dequeue() into the bullet variable. Then print the used bullet and remaining count with Console.WriteLine.
Starter code
using System;
using System.Collections.Generic;
class ObjectPoolDemo
{
static void Main()
{
Queue<string> pool = new Queue<string>();
pool.Enqueue("Mermi_1");
pool.Enqueue("Mermi_2");
// Havuzdan nesne cek ve ekrana kalanla birlikte yazdir
}
}Sample solution
using System;
using System.Collections.Generic;
class ObjectPoolDemo
{
static void Main()
{
Queue<string> pool = new Queue<string>();
pool.Enqueue("Mermi_1");
pool.Enqueue("Mermi_2");
string bullet = pool.Dequeue();
Console.WriteLine($"Kullanilan: {bullet} | Kalan: {pool.Count}");
}
}Expected output
Kullanilan: Mermi_1 | Kalan: 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the primary purpose of the Object Pooling pattern?
- Prevent Instantiate and Destroy overhead along with GC stutters Correct answer
- Automatically reduce polygon count on screen to zero
- Merge all C# classes into a single file
- Disable physics collisions for all objects in the scene
Explanation: Object Pooling reuses pre-allocated objects to prevent memory allocation and Garbage Collection spikes.
2 Create queue pool
Queue<string> pool = new ____();
Queue<string> pool = new Queue<string>();
Explanation: A Queue collection is instantiated for pool management using FIFO (first-in first-out) order.
3 Pool components
| Term | Meaning |
|---|---|
Object Pool |
Pool where reusable objects are stored |
SetActive(false) |
Hides the object without destroying it |
Garbage Collector |
Cleans unreferenced memory blocks |
Instantiate |
Creates a new object instance |