Home Game Development c# – How to Refactor a Unity PoolManager Class for Generic Object Pooling?

c# – How to Refactor a Unity PoolManager Class for Generic Object Pooling?

0
c# – How to Refactor a Unity PoolManager Class for Generic Object Pooling?

[ad_1]

I’d like to refactor my pooling class to work for more object types in my top down Unity game. Right now its working fine for player projectiles, but I want it to also work for enemy projectiles, enemies, particle effects, basically anything that may spawn and be destroyed. I also feel that its rather clunky to assign the projectilePrefab directly in the manager, so I was also wondering if something like an Interface like IPoolable would be the way to go.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Pool;

public class PoolManager : MonoBehaviour
{
    #region Pooled Objects

    [SerializeField] private Projectile _projectilePrefab;
    [SerializeField] private Enemy _enemyPrefab;

    private ObjectPool<Projectile> _projectilePool;
    private ObjectPool<Enemy> _enemyPool;

    #endregion

    [SerializeField] private int _projectilePoolAmount;
    [SerializeField] private bool _usePool = true;

    public static PoolManager Instance { get; private set; }
    private GameObject _poolContainer;

    void Awake()
    {
        Instance = this;

        _poolContainer = new GameObject($"PoolContainer - {_projectilePrefab.name}");
        _poolContainer.transform.SetParent(transform);

        InitializeProjectilePool();
    }

    private void InitializeProjectilePool()
    {
        _projectilePool = new ObjectPool<Projectile>(
            CreateProjectile,
            projectile => {
                projectile.gameObject.SetActive(true);
            }, projectile => {
                projectile.gameObject.SetActive(false); 
            }, projectile => {
                Destroy(projectile.gameObject); 
            }, false, 10, 200);
    }

    private Projectile CreateProjectile()
    {
        Projectile projectileInstance = Instantiate(_projectilePrefab);
        projectileInstance.transform.SetParent(_poolContainer.transform);
        projectileInstance.gameObject.SetActive(false);
        return projectileInstance;
    }
    private void KillProjectile(Projectile projectile)
    {
        if (_usePool) { _projectilePool.Release(projectile); }
        else { Destroy(projectile.gameObject); }
    }

    public Projectile GetProjectile()
    {
        var projectile = _usePool ? _projectilePool.Get() : CreateProjectile();
        projectile.Init(KillProjectile);
        return projectile;
    }
}

[ad_2]