df23868b40
fix: update spawn NPC.
2.6 KiB
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
- A caller accesses
PrefabPoolManager.Instance. - If no manager exists in the scene, the singleton creates a
PrefabPoolManagerGameObject and marks it withDontDestroyOnLoad. - The caller may pre-warm a prefab pool by calling:
PrefabPoolManager.Instance.InitPool(prefab, defaultCapacity, maxSize);
InitPoolcreates oneObjectPool<GameObject>for the prefab and preloads inactive instances under a prefab-specific container.- The caller spawns instances by calling:
GameObject obj = PrefabPoolManager.Instance.Spawn(prefab, position, rotation);
Spawninitializes 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.- The caller returns instances by calling:
PrefabPoolManager.Instance.Despawn(obj);
Despawnreleases the instance back to its original pool, disables it, and reparents it under the prefab pool container.- If the pool exceeds
maxSize, Unity'sObjectPooldestroys 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
InitPoolduring loading screens or scene setup for frequently spawned prefabs. - Use
Spawninstead ofInstantiate. - Use
Despawninstead ofDestroyfor 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.