Creating A Simple Unity Object Pooling Class for Flappy Jetroid

Taking a quick break to go back and clean up the code in my Flappy Bird clone, Flappy Jetroid. I was seeing some minor performance issues on mobile, especially when creating all exploding body parts on the fly so I implemented a simple C# object pooling class in Unity.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
 
public class ObjectPool : MonoBehaviour {
 
	public int poolSize = 5;
	public GameObject[] instances;
	public bool prePopulate;
 
	private List<gameobject> poolInstances = new List</gameobject><gameobject> ();
 
	void Start () {
		if (prePopulate)
			PrePolpulate ();
	}
 
	public void PrePolpulate(){
		for (var i = 0; i < poolSize; i++){
			var clone = CreateInstance();
			clone.SetActive(false);
			clone.transform.parent = transform;
		}
	}
 
	public GameObject NextObject(){
 
		foreach (var instance in poolInstances) {
			if(instance.activeSelf != true){
				return instance;
			}
		}
 
		return CreateInstance ();
	}
 
	private GameObject CreateInstance(){
		var clone =  Instantiate (instances [Random.Range (0, instances.Length)], Vector2.zero, Quaternion.identity) as GameObject;
		poolInstances.Add (clone);
		return clone;
	}
 
}

Here is an example of how I use it to pre-populate the body parts used in the explosion:

var poolGameObject = new GameObject("BodyParts");
pool = poolGameObject.AddComponent("ObjectPool") as ObjectPool;
pool.poolSize = totalParts;
pool.instances = new GameObject[1]{bodyPart};
pool.PrePolpulate ();

I am also using this for the walls in my game. You can see it in action here:

object-pooling

Noticed on the left in the hierarchy Tab how the wall instances are greyed out then become active and inactive again as they go off the screen. This kind of object pooling is critical for mobile devices so hopefully it helps you out.

Looking to learn more about Unity and making 2D games? Check out my video series:

Lynda Unity 2D Essential Training

Subscribe To My Mailing List

Want to learn how to make a game? Not sure where to start? Even if you are a seasoned game maker there is still a lot you can learn from my mailing list. I'll be covering tips and tricks for how to build, release and market games each month.

Simply sign up for my mailing list and also get access to a 50% off discount code for my eBooks and other content. I promise to not spam your inbox!

Join Now