Objet Pooling in Unity3D

When you have lots of prefabs creation and destruction going on at runtime in Unity3D, things can get laggy. Or at least, it's inneficient! That's where a pooling system comes in handy. Object pooling means to recycle objects to avoid the performance drop. Concretely, it means to deactivate objects instead of destroying them when they have achieved their purpose and when you want to create a new instance of an object, you check if a disabled version of it is available to be recycled.

So I've made a simple C# script called PoolingManager.cs that does the job for you.

To use it, create a new empty object in the scene hierarchy and attach the PoolingManager script to it. Once this is done, simply call the Provide function of the PoolingManager singleton from anywhere in your code like so :

GameObject newObject = PoolingManager.Instance.Provide(myPrefab); //Initialize newObject and do other stuffs here

The Provide(Transform pPrefab) method will look if a unused(disabled) object of that same prefab name exists in the scene and if not, it will instanciate a new object with that prefab. The only thing you have to take care is to disable objects instead of destroying so the PoolingManager can reuse them. Also, if you have a script attached to your prefab and it does things in the Start() method, transfer these things in the OnEnable() method so the code you want to run when an object appears will happen even if it's a recycled instance. If everything goes well, your scene should look like this while playing :

When the player dies and you want to reset the level, you can simply call PoolingManager.Instance.DeactivateAllObjects() to disable all instancied objects at once, making them available for use again.

Download linkPoolingManager.cs