-
Notifications
You must be signed in to change notification settings - Fork 0
Object Pool pattern
The object pool pattern is used when we want to instantiate a lot of objects. The instantiation and destroy of objects is a really expensive proccess, this pattern will help us reducing that expense. The pattern could be used for example in a particle system, in a enemy spawner, in a projectile system, etc.
The pattern works by instantiating a certain number of objects to be used later, called pool. When we want one of this objects, we ask the object pool manager to activate this object and give it to us. As simple as this:

In our example we will examine cube spawner that will scale every cube until it gets to a certain scale, the it will destroy it. In the implementation of this object pooler I decided to be able to instantiate more objects in case we need it. I decided also to be able to say if we need the objects that our object pool has used, to be preserved or not. In case we don't, the currently used objects can be given as to another class as a new pooled object. This last ability is implemented in my code by the use of a list, but its better to use a Queue to this proccess. Here is the code of the object pool:
private void Awake() {
pool = new List();
for(int i = 0; i < size;i++){
GameObject cube = Instantiate(cubePrefab,this.transform);
cube.SetActive(false);
pool.Add(cube);
}
}
public GameObject GetCubeFromPool(){
if (needForPreserveCubes)
{
GameObject newCube = pool[0];
pool.Remove(newCube);
setCube(newCube);
pool.Add(newCube);
return newCube;
}
for (int i = 0; i < pool.Count; i++)
{
if (!pool[i].gameObject.activeInHierarchy)
{
setCube(pool[i]);
return pool[i];
}
}
if (shouldExpand)
{
GameObject newCube = Instantiate(cubePrefab,this.transform);
pool.Add(newCube);
setCube(newCube);
return newCube;
}
else
return null;
}
private void setCube(GameObject cube){
cube.SetActive(true);
cube.transform.position = Vector3.zero;
cube.transform.position += new Vector3(Random.Range(-20,20),0,Random.Range(-20,20));
cube.transform.localScale = new Vector3(1,1,1);
}Home
C#
Game Design Patterns
- Command
- Flyweight pattern & Scriptable Objects
- Observer pattern
- State pattern
- Object Pool pattern
- Factory pattern
ECS
PlayFab
- Introduction
- Template Class
- Player Authentication
- Mobile Authentication
- Player Statistics
- Leaderboard
- Player Data
- Friends
Mirror