Day 48 | Object Pooler: 2D Space Shooter Series 15

Ted Lim
2 min readJun 27, 2021

The next feature for our game is a boss battle. Part of the boss battle will include a bullet hell situation where players will dodge a swarm of bullets. To implement the bullet behavior, we will utilize a design pattern known as object pooling.

What is Object Pooling

Object Pooling is the idea of pre-initializing objects so that you don’t have to create and destroy them during runtime. Bullet-hell behavior involves the creation and destruction of many objects during runtime, which can be costly. Object Pooling provides pre-existing objects for the shooting behavior, which should help improve our game’s performance.

Implementation

Here’s the idea for the pseudocode for object pooling and how I converted it to code:

1.Create a container list (pool) for your object, add a stock amount of objects, and set them inactive.

2. Anytime a client or another script needs the object, check the pool for an existing but disabled version of the object.

3. If it exists, return the object for use; otherwise, create a new object, add it to the pool, and return it for use.

4. We can then add a public static reference to an instance of the Object Pooler for easier accessibility.

With this setup, we can then create another script that will shoot the bullets and use the objects in the pool to populate the game scene. Assuming you have a basic movement script on the bullet, one way to spawn the bullets would be to use a coroutine with a while loop to access the objects in the pool at a given rate.

void Start()
{
StartCoroutine(Shoot());
}
IEnumerator Shoot(){
while (true)
{
GameObject obj = ObjectPoolerScript._sharedInstance.GetPooledObject();
obj.transform.position = transform.position;
obj.transform.rotation = transform.rotation;
obj.SetActive(true);
yield return new WaitForSeconds(.1f);
}
}

This is what it looks like.

Maybe a little uninspiring for now, but this will improve the performance of our game in the long run. In the next article, we’ll go over how to make more interesting types of shooting patterns.

--

--