Tuesday 31 January 2017

Simple solution for instantiate/ recycling Game object in Unity

I have been looking for an efficient way of generating bullets and recycling them in Unity environment for a while. And finally, here's a very good and easy solution for that.

Target:
Different mobs shoot different types of bullets towards player. A reusable solution is needed for managing the bullets instantiation and destroying.

Solution:
Instead of adding a script for the mob to generate and destroy bullets, use a bullet pool to manage the generating and destroying of bullets. Every time a mob shoots, the mob class asks the pool for a new bullet. Pool checks itself for available bullets. If there is a bullet, it is passed to the mob, otherwise a bullet need to be instantiated before it is passed to the mob. When the bullet's life cycle is complete (either time out or hit objects) it returns itself to the pool.

Implementation
1.The Pool :
The Pool is an empty Gameobject on the stage. The Pool class has a stack and two public functions: getObject() and returnObject().
stack:
keeps the instances of bullets.
getObject():
check available bullets, instantiate bullets, pop the required bullet out of stack, and return it to Mob as an Gameobject.
 returnObject():
to push the object back to stack.

2.The Mob class:
The Mob class holds an instance of the pool on the stage. At the Moment of attacking, it calls the getObject() function to acquire a bullet and set the transform of the bullet.

3.The Bullet class:
The Bullet class holds an instance of the pool on the stage. It starts to move forward as soon as it is acquired by the Mob. When it hits something, it hides itself and calls the returnObject () function.

the result:

 

the source code for the pool: