PoolSystem

This class provides static methods for getting gameobjects and returning them back to pool.

Instance pooling is very good practice to squeeze better performance in case if you need to spawn objects frequently (like projectiles in shooter game or something like this).

Available methods

public static void ResetPools(bool destroyImmediately = true)

This method clears all created pools.


public static T GetInstance<T>(T prefab, string name) where T : MonoBehaviour, IPooledObject

This method returns an instance of class T which is inherited from MonoBehaviour and IPooledObject, and presented by certain prefab. It tries to get such object from pool with assigned name, in case if such pool isn't found, it creates new pool with this name.

Example:

var resourceUISlot = PoolSystem.GetInstance(resourceSlotPrefab, resourceSlotPrefab.GetName());

public static T GetObj<T>(string name) where T : MonoBehaviour, IPooledObject

This method returns an available instance of class T which is inherited from MonoBehaviour and IPooledObject, and contained in pool with name.

Example:

var explosion = PoolSystem.GetObj<PooledParticleSystem>("Explosion");

explosion.transform.position = targetPos;

public static void ReturnToPool<T>(T obj) where T : MonoBehaviour, IPooledObject

This method returns gameobject obj of given type T to pool. This gameobject will be immediately deactivated after this.

Example:

enemy.GetDamage(bullet.Damage);
bullet.Explode();

PoolSystem.ReturnToPool(bullet); //We return projectile back to pool after collision

public static T GetInstanceAtPosition<T>(T prefab, string name, Vector3 pos, Transform parent = null) where T : MonoBehaviour, IPooledObject

This method returns an available instance of given prefab from pool with name, moves this instance to given world position and sets certain parent transform. If parent is null, it leaves instance in previously assigned parent transform.

Example:

var bullet = PoolSystem.GetInstanceAtPosition<Projectile>(bulletPrefab,
    bulletPrefab.GetName(),
    muzzleTransform.position);

bullet.Launch(targetTransform.position);

public static T GetInstanceAtPosition<T>(T prefab, string name, Vector3 pos, Quaternion rotation, Transform parent = null) where T : MonoBehaviour, IPooledObject

This method returns an available instance of given prefab from pool with name, moves this instance to given world position, rotation and sets certain parent transform. If parent is null, it leaves instance in previously assigned parent transform.

Example:

var bullet = PoolSystem.GetInstanceAtPosition<Projectile>(bulletPrefab,
    bulletPrefab.GetName(),
    muzzleTransform.position,
    Quaternion.LookRotation(targetTransform.position - muzzleTransform.position));

bullet.Launch(targetTransform.position);

Last updated