Game Development
Challenge 1: Object pool
Write a simple object pool class.
The object pool idea
Object pooling is the technique of keeping objects in a pool and reusing them instead of destroying them. A pool is usually built with the Queue structure; when needed an object is taken from the line with Dequeue and put back with Enqueue when the job is done. This way a new allocation is not needed every time.
Queue<string> havuz = new Queue<string>();
havuz.Enqueue("Kutu");
string nesne = havuz.Dequeue();
This method reduces the memory load for frequently created objects.
Exercise Simple pool class
In a class named NesneHavuzu, define a queue field named havuz. Write a method named Al that takes an object from the pool and returns it. In Start, add "Kutu1" to the pool, take an object with Al into a variable named alinan and print the text "Alinan: " joined with alinan using Debug.Log.
Show example solution
using UnityEngine;
using System.Collections.Generic;
public class NesneHavuzu : MonoBehaviour
{
private Queue<string> havuz = new Queue<string>();
string Al()
{
return havuz.Dequeue();
}
void Start()
{
havuz.Enqueue("Kutu1");
string alinan = Al();
Debug.Log("Alinan: " + alinan);
}
}
Exercise Pool reuse
In a class named HavuzSayaci, define a queue field named havuz and an integer field named yenidenKullanilan. In Start, add "Kasa" to the pool, take an object with Dequeue, put it back with Enqueue, increase yenidenKullanilan by one and print the text "Yeniden kullanilan: " joined with that variable using Debug.Log.
Show example solution
using UnityEngine;
using System.Collections.Generic;
public class HavuzSayaci : MonoBehaviour
{
private Queue<string> havuz = new Queue<string>();
int yenidenKullanilan;
void Start()
{
havuz.Enqueue("Kasa");
string nesne = havuz.Dequeue();
havuz.Enqueue(nesne);
yenidenKullanilan = yenidenKullanilan + 1;
Debug.Log("Yeniden kullanilan: " + yenidenKullanilan);
}
}
Test yourself
-
What happens when an object is returned to an object pool?
- The object is put back into the pool and waits to be reused
- A new allocation is made
- The object is destroyed and memory is reclaimed
- The pool closes permanently
Show answer
The object is put back into the pool and waits to be reused — In pooling the object is not destroyed; it is added back to the line with Enqueue and taken again in the next use.
-
Adding to the pool
havuz.____("Kutu1");
Show answer
havuz.Enqueue("Kutu1");
-
Pool terms
- Queue
- A collection that works in FIFO order
- Enqueue
- Add element to queue / return to pool
- Dequeue
- Remove element from front of queue
- Object Pool
- The structure where objects are reused
Next lesson: Challenge 2: ECS component