Files
test/Documentation/PrefabsPoolingManager.md
Tungdv df23868b40 feat: Add prefabs pooling manager.
fix: update spawn NPC.
2026-05-06 15:33:28 +07:00

2.6 KiB

Prefabs Pooling Manager

Purpose

PrefabPoolManager centralizes prefab spawning and despawning through UnityEngine.Pool.ObjectPool. Any gameplay code that repeatedly creates or removes prefab instances should use this manager instead of direct Instantiate and Destroy calls.

Runtime Flow

  1. A caller accesses PrefabPoolManager.Instance.
  2. If no manager exists in the scene, the singleton creates a PrefabPoolManager GameObject and marks it with DontDestroyOnLoad.
  3. The caller may pre-warm a prefab pool by calling:
PrefabPoolManager.Instance.InitPool(prefab, defaultCapacity, maxSize);
  1. InitPool creates one ObjectPool<GameObject> for the prefab and preloads inactive instances under a prefab-specific container.
  2. The caller spawns instances by calling:
GameObject obj = PrefabPoolManager.Instance.Spawn(prefab, position, rotation);
  1. Spawn initializes a pool automatically if the prefab has not been registered yet, gets an object from the pool, detaches it from the pool container, sets its transform, and activates it.
  2. The caller returns instances by calling:
PrefabPoolManager.Instance.Despawn(obj);
  1. Despawn releases the instance back to its original pool, disables it, and reparents it under the prefab pool container.
  2. If the pool exceeds maxSize, Unity's ObjectPool destroys extra released instances.

API

public void InitPool(GameObject prefab, int defaultCapacity = 10, int maxSize = 50);
public GameObject Spawn(GameObject prefab, Vector3 position, Quaternion rotation);
public void Despawn(GameObject obj);

Usage Example

public class ProjectileSpawner : MonoBehaviour
{
    [SerializeField] private GameObject projectilePrefab;

    private void Start()
    {
        PrefabPoolManager.Instance.InitPool(projectilePrefab, 20, 100);
    }

    public void Fire(Vector3 position, Quaternion rotation)
    {
        GameObject projectile = PrefabPoolManager.Instance.Spawn(projectilePrefab, position, rotation);
        projectile.SetActive(true);
    }

    public void Release(GameObject projectile)
    {
        PrefabPoolManager.Instance.Despawn(projectile);
    }
}

Notes

  • Use InitPool during loading screens or scene setup for frequently spawned prefabs.
  • Use Spawn instead of Instantiate.
  • Use Despawn instead of Destroy for objects created through this manager.
  • Each prefab has its own independent pool and capacity limits.
  • The system is intended for mobile targets, where avoiding frequent allocations helps reduce frame spikes and garbage collection pressure.