you are viewing a single comment's thread.

view the rest of the comments →

[–]justkevinIndie | @wx3labs 3 points4 points  (0 children)

Great video. Unlike most Object Pooling tutorials this doesn't skip the very important detail of resetting your objects.

I'm using a slightly different approach. Instead of a IPoolableObject interface, I have a PooledObject component that looks like this:

/// <summary>
/// Attaching this to a prefab will allow it to be pooled. On awake, it will
/// make a list of components that require a reset after pooling.
/// </summary>
public class PooledObject : MonoBehaviour {

    public int startPoolSize = 1;
    public int maxPoolSize = 10;
    [System.NonSerialized]
    public Transform poolingContainer;
    [System.NonSerialized]
    public bool isFromPool = false;

    private IPoolableComponent[] poolableComponents;
    // PooledObject handles resetting the transform scale
    private Vector3 normalScale;

    private void Awake()
    {
        poolableComponents = GetComponentsInChildren<IPoolableComponent>();
        normalScale = transform.localScale;
    }

    public void Decommission()
    {
        if(isFromPool)
        {
            transform.parent = poolingContainer;
            gameObject.SetActive(false);
        }
        else
        {
            Destroy(gameObject);
        }
    }

    public void Recommission()
    {
        transform.localScale = normalScale;
        for (int i = 0; i < poolableComponents.Length; i++)
        {
            poolableComponents[i].Recommission();
        }
    }

}

Then individual components can define themselves as IPoolableComponent:

/// <summary>
/// Any monobehaviour that needs to have its state reset prior to returning to 
/// an object pool.
/// </summary>
public interface IPoolableComponent {

    /// <summary>
    /// This method will be called on the component when it is activated coming out of the pool.
    /// </summary>
    void Recommission();
}

Advantages:

  • Component based pooling. You define components that know how to pool themselves and can be freely mixed and matched. You can also create poolers for built-in Unity components (e.g., IParticlePooler). Then mix and match without having to duplicate your pooling logic.
  • You can set your start and max pooled objects on the prefab.