Time for action – Optimizing with the object pool

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.

  1. Connect the game to the profiler following the previous Time for action and run it, firing a large number of projectiles:
    Time for action – Optimizing with the object pool

    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.

  2. Create a GameObject called PoolManager:
    Time for action – Optimizing with the object pool
  3. Add the ObjectPool script to the PoolManager:
    Time for action – Optimizing with the object pool
  4. Add the prefabs that you want to pool to the Object Prefabs array. You can accomplish this by dragging a prefab from the Hierarchy view onto the Object Prefabs array:
    Time for action – Optimizing with the object pool
  5. Replace the existing 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.

  6. Start the game again and look at the Profiler profile. Fire a lot of projectiles and examine the performance.

What just happened?

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.111.134