audio toolkit header
HOW TO USE DOCUMENTATION BUY

Object Pooling Class

 

What is pooling?

GameObject.Instantiate(...) calls are relatively time expensive. If objects of the same type are frequently created and destroyed it is good practice to use object pools, particularly on mobile devices. This can greatly reduce the performance impact for object creation and garbage collection.

How does pooling work?

Instead of actually destroying object instances, they are just set inactive and moved to an object "pool". If a new object is requested it can then simply be pulled from the pool, instead of creating a new instance.
Awake(), Start() and OnDestroy() are called if objects are retrieved from or moved to the pool just like they were instantiated and destroyed normally.

Examples

How to set up a prefab for pooling:

  1. Add the PoolableObject script component to the prefab to be pooled. You can set the maximum number of objects to be stored in the pool from within the inspector.
    Beschreibung: C:\SVN_Repositories\UnityAssetStore\Assets\AudioToolkit\AssetStore\Screenshots\PoolableAudioObject.png
  2. Replace all Instantiate( myPrefab ) calls with ObjectPoolController.Instantiate( myPrefab )
  3. Replace all Destroy( myObjectInstance ) calls with ObjectPoolController.Destroy( myObjectInstance )
  4. Use the ObjectPoolController.Preload( myPrefab ) function to preload as many instances of a prefab as specified in the PoolableObject.

Attention: Be aware that:

  • All data must get initialized in the Awake() or Start() function
  • OnDestroy() will get called a second time once the object really gets destroyed by Unity
  • If a poolable objects gets parented to none-poolable object, the parent must be destroyed using ObjectPoolController.Destroy( ... ) even if it is none-poolable itself.
  • If you store a reference to a poolable object then this reference does not evaluate to null after Destroy was called like other references to Unity objects normally would. This is because the object still exists - it is just in the pool. To make sure that a stored reference to a poolable object is still valid you must use PoolableReference.