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

[ad_1]

I might prefer to refactor my pooling class to work for extra object varieties in my prime down Unity sport. Proper now its working superb for participant projectiles, however I need it to additionally work for enemy projectiles, enemies, particle results, mainly something that will spawn and be destroyed. I additionally really feel that its slightly clunky to assign the projectilePrefab straight within the supervisor, so I used to be additionally questioning if one thing like an Interface like IPoolable can be the way in which to go.

utilizing System.Collections;
utilizing System.Collections.Generic;
utilizing UnityEngine;
utilizing UnityEngine.Pool;

public class PoolManager : MonoBehaviour
{
    #area Pooled Objects

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

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

    #endregion

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

    public static PoolManager Occasion { get; personal set; }
    personal GameObject _poolContainer;

    void Awake()
    {
        Occasion = this;

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

        InitializeProjectilePool();
    }

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

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

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

[ad_2]

Categories:

Leave a Reply

Your email address will not be published. Required fields are marked *