Simple Pool of Prefabs for Unity3D

Recently I faced a pooling problem in my game. My prefabs were instantiated at run time and it caused some performance issues. Thats why I decided to implement a simple pool of prefabs myself as other pools had a significant overhead in functionality for my project. The implementation is ported from Nicolas Gramlich’s Andengine pool implementation. The project below also contains an example of how to use this pool.

Simple Pool of Prefabs for Unity3D Game Engine on GitHub.

 

The usage is extremely simple. First you create an instance of PrefabPool (there are overloaded constructors for flexibility). The constructor with all parameters:

What we have now is a set of instantiated and inactive objects. We do this when our game is loading to avoid further runtime prefab instantiations. We also pass a parent transform to constructor to avoid all these clones being located in Hierarchy root.

Ok, now when out pool of cubes is ready to use we are ready to obtain items from it.

 

As you can see in the hierarchy these three cubes were retrieved from the pool and not instantiated:

If you try to obtain instance from the pool when it is full, the pool will grow by the growth value specified in the constructor. Now the only thing that is left is to recycle instances. Their position and scale will be reset to Vector3.zero , rotation to Quaterniont.identity and they will become inactive. Code to recycle items:


This is what the picture looks like after recycling:

Summary: This project provides a simple implementation for pool of prefabs to avoid performance issues with run-time prefab instantiation.

P.S. There may be some parenting issues (when changing items parent – with transform, layers, etc).

  • Taras Leskiv

    Send me a pull request or link if you do so:) Glad it was useful.