Object Pooling with child classes?

I’m trying to set up a pooling system for tiles in the level of a runner game. I have a parent class Tile, which I set up a pool for below:

private ObjectPool<Tile> _tilePool;
_tilePool = new ObjectPool<Tile>(
            createFunc: () => {
                var newTile = Instantiate(templateTile);
                newTile.gameObject.SetActive(true);
                newTile.transform.parent = _tilePoolTransform;
                newTile.transform.localPosition = Vector3.zero;
                return newTile;
            },
            actionOnGet: (obj) => {
                obj.gameObject.SetActive(true);
            },
            actionOnRelease: (obj) => {
                obj.transform.parent = _tilePoolTransform;
                obj.transform.localPosition = Vector3.zero;
                obj.gameObject.SetActive(false);
            },
            actionOnDestroy: (obj) => Destroy(obj.gameObject), 
            collectionCheck: false,
            defaultCapacity: 50,
            maxSize: 100
            );

The problem is, Tile has many subclasses, such as SpikeTile, EnemyTile, CoinTile, and this object pool doesn’t seem to let me spawn and recycle them. What’s the best way to set up a pool that lets me access all these subclasses?

1 Like

One way you could implement object pooling with child classes is to create a separate object pool for each child class.

For example, you could create an object pool for SpikeTile, an object pool for EnemyTile, and so on. You would then create a function for each object pool that follows the same pattern as the createFunc function you provided in your example code.

Alternatively, you could create a single object pool that is able to handle all of the different child classes. To do this, you could use a generic type parameter when defining the object pool class, like this:

public class ObjectPool<T> where T : Tile
{
    // object pool implementation here
}

Then, when you instantiate the object pool, you would specify the type of the child class that you want to pool, like this:

var spikeTilePool = new ObjectPool<SpikeTile>(
    createFunc: () => {
        // create a new SpikeTile object here
    },
    // other parameters here
);

var enemyTilePool = new ObjectPool<EnemyTile>(
    createFunc: () => {
        // create a new EnemyTile object here
    },
    // other parameters here
);

With this approach, you can use the same object pool to pool objects of different child classes, as long as they all derive from the Tile class.