Pseudocode Example

In order to use an Object Pool, the objects being created must be reusable and have both an ‘in-use’ and a ‘not-in-use’ state. For this example we will continue with the function to produce a decal when a bullet collides with a wall. The ‘not-in-use’ state for the decal could be a boolean flag set to false and the alpha set to 0 or renderers turned off in order to hide it from player view. The ‘in-use’ state would be the opposite, the boolean flag set to true and the decal visible to players.

For example, take the following pseudo-code for showing a decal which does not use an object pool:

function showDecal
     create Decal Object named decalObject
     move decalObject to the desired location
     wait for a length of time
     destroy decalObject
end function

If called in rapid succession, this function would not only be slow due to using the relatively expensive operations of creating and destroying an object. Over time, this could also cause memory fragmentation as many small sections of memory are used up and then freed.

The same operation could be re-written using Object Pooling in the following way:

create array of Decal Objects named decalObjectArray
initialise each DecalObject in decalObjectArray and set its state to 'not-in-use'
function showDecal
    find DecalObject in decalObjectArray which is not in use
    assign this DecalObject to a variable named decal
    set the state of decal to be 'in-use'
    move decal to the desired location
    wait for a length of time
    set the state of decal to be 'not-in-use'
 end function
goodflow
This way, all memory required for a full set of decals is created on start-up so memory fragmentation is avoided. It also means that most of the intensive operations are done on start-up (initialising Decal Objects) and exit (destroying Decal Objects), ensuring that minimal slowdown occurs during gameplay.

Leave a comment