Now that we have a game object pool and the ability to profile our application we can look at how this optimization improves our application's performance. We will do this by replacing the GameObject
instantiation approach that we took to creating projectiles when the player fires his weapon.
What we can see from this object profile is that performance dips considerably when the weapon is fired. The reason for this is because we are creating GameObjects on the fly. We can see here that when these objects are removed from view and collected, the performance of the application becomes more consistent. Things like this are a smoking gun and we have an optimization that can be made to improve performance of the game.
fireWeapon
script with the optimized fireWeapon
script that uses the Object Pool:void fireWeapon() { GameObject bullet = ObjectPool.instance.GetObjectForType( "Bullet" , true); bullet.transform.position = spawnPoint.transform.position; bullet.transform.rotation = spawnPoint.transform.rotation; }
What we have done here is replace the
GameObject.Instantiate()
method that we were originally using for creating new bullets from our weapon.
We have just improved the performance of our application using object pooling. As you can see, the performance of the application is consistent now. This is what we are aiming for – a consistent frame rate.
Instead of paying the penalty for creating and deleting large numbers of GameObject
instances, we are instead creating a pool of those objects and simply changing their position, rotation, state, and visibility. This is an old trick that was frequently employed in gaming that was lost in the age of modern computers and graphics capabilities, but is just what we need on mobile devices to ensure optimal performance.
18.222.111.134