Code

Code

I was recently working on a project requiring spawning and despawning lots of objects.  Obviously doing so is WAY less efficient than simply recycling existing objects, so I wrote a nice system to pool gameobjects.  The system is comprised of 3 parts:

  • There is a PooledObject component, which goes on any gameobject we wish to pool.
  • There is an IPooledComponent interface, which will go on any component requiring resetting when the gameobject is recycled.
  • Then there is the ObjectPooler itself, which provides a nice API for the rest of the codebase to fetch gameobjects from a pool.

The API allows you to just ask for a gameobject, and if it’s not a pooled object, it will add the PooledObject component, create a pool, and return one of the objects from the pool’s stack.  I wish to keep most of the code closed source for now, but I’ve provided a representative excerpt below.  This code is written for Unity in C#.