84 lines
2.1 KiB
C#
84 lines
2.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
|
|
using UnityEngine;
|
|
|
|
public class ObjectPooler : MonoBehaviour
|
|
{
|
|
[Serializable]
|
|
public struct PoolConfig
|
|
{
|
|
public GameObject Prefab;
|
|
public int PoolSize;
|
|
}
|
|
|
|
public PoolConfig[] PoolConfigs;
|
|
|
|
public static ObjectPooler Instance;
|
|
|
|
private Dictionary<GameObject, Queue<GameObject>> pools;
|
|
|
|
public GameObject Request(GameObject prefab, Transform parent)
|
|
{
|
|
Debug.Assert(pools.ContainsKey(prefab), "No pool configured for this prefab");
|
|
|
|
var wantedPool = pools[prefab];
|
|
Debug.Assert(wantedPool.Count > 0, "Pool size too small! (prefab: " + prefab + ")");
|
|
|
|
var newObject = wantedPool.Dequeue();
|
|
newObject.transform.SetParent(parent, false);
|
|
newObject.SetActive(true);
|
|
|
|
return newObject;
|
|
}
|
|
|
|
public void Release(GameObject prefab, GameObject returnedObject)
|
|
{
|
|
returnedObject.SetActive(false);
|
|
returnedObject.transform.SetParent(transform, false);
|
|
pools[prefab].Enqueue(returnedObject);
|
|
}
|
|
|
|
private void Awake()
|
|
{
|
|
Debug.Assert(Instance == null, "Multiple instances of the ObjectPooler!");
|
|
Instance = this;
|
|
}
|
|
|
|
private void Start()
|
|
{
|
|
pools = new Dictionary<GameObject, Queue<GameObject>>();
|
|
|
|
// preallocate all pooled objects
|
|
foreach (var poolConfig in PoolConfigs)
|
|
AllocatePool(poolConfig.Prefab, poolConfig.PoolSize);
|
|
}
|
|
|
|
private void AllocatePool(GameObject prefab, int size)
|
|
{
|
|
var newList = new Queue<GameObject>();
|
|
for (var i = 0; i < size; i++)
|
|
{
|
|
var newObject = Instantiate(prefab);
|
|
newObject.SetActive(false);
|
|
newObject.transform.SetParent(transform, false);
|
|
newList.Enqueue(newObject);
|
|
}
|
|
|
|
pools.Add(prefab, newList);
|
|
}
|
|
|
|
private void OnDestroy()
|
|
{
|
|
// destroy all pooled objects
|
|
foreach (var entry in pools)
|
|
{
|
|
foreach (var item in entry.Value)
|
|
{
|
|
Destroy(item);
|
|
}
|
|
}
|
|
|
|
pools.Clear();
|
|
}
|
|
}
|