df23868b40
fix: update spawn NPC.
75 lines
2.6 KiB
Markdown
75 lines
2.6 KiB
Markdown
# 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:
|
|
|
|
```csharp
|
|
PrefabPoolManager.Instance.InitPool(prefab, defaultCapacity, maxSize);
|
|
```
|
|
|
|
4. `InitPool` creates one `ObjectPool<GameObject>` for the prefab and preloads inactive instances under a prefab-specific container.
|
|
5. The caller spawns instances by calling:
|
|
|
|
```csharp
|
|
GameObject obj = PrefabPoolManager.Instance.Spawn(prefab, position, rotation);
|
|
```
|
|
|
|
6. `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.
|
|
7. The caller returns instances by calling:
|
|
|
|
```csharp
|
|
PrefabPoolManager.Instance.Despawn(obj);
|
|
```
|
|
|
|
8. `Despawn` releases the instance back to its original pool, disables it, and reparents it under the prefab pool container.
|
|
9. If the pool exceeds `maxSize`, Unity's `ObjectPool` destroys extra released instances.
|
|
|
|
## API
|
|
|
|
```csharp
|
|
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
|
|
|
|
```csharp
|
|
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.
|