50 lines
1.5 KiB
C#
50 lines
1.5 KiB
C#
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class GenericObjectPool : MonoBehaviour
|
|
{
|
|
public static GenericObjectPool Instance;
|
|
|
|
[System.Serializable]
|
|
public class Pool
|
|
{
|
|
public string tag;
|
|
public GameObject prefab;
|
|
public int size;
|
|
}
|
|
|
|
public List<Pool> pools;
|
|
public Dictionary<string, Queue<GameObject>> poolDictionary;
|
|
|
|
private void Awake()
|
|
{
|
|
Instance = this;
|
|
poolDictionary = new Dictionary<string, Queue<GameObject>>();
|
|
|
|
foreach (Pool pool in pools)
|
|
{
|
|
Queue<GameObject> objectPool = new Queue<GameObject>();
|
|
for (int i = 0; i < pool.size; i++)
|
|
{
|
|
GameObject obj = Instantiate(pool.prefab);
|
|
obj.SetActive(false); // 꺼둔 상태로 보관
|
|
objectPool.Enqueue(obj);
|
|
}
|
|
poolDictionary.Add(pool.tag, objectPool);
|
|
}
|
|
}
|
|
|
|
// ⭐ 몹을 꺼내 쓸 때 호출 (Instantiate 대신 사용)
|
|
public GameObject SpawnFromPool(string tag, Vector3 position, Quaternion rotation)
|
|
{
|
|
if (!poolDictionary.ContainsKey(tag)) return null;
|
|
|
|
GameObject objectToSpawn = poolDictionary[tag].Dequeue();
|
|
objectToSpawn.SetActive(true);
|
|
objectToSpawn.transform.position = position;
|
|
objectToSpawn.transform.rotation = rotation;
|
|
|
|
poolDictionary[tag].Enqueue(objectToSpawn); // 다시 큐의 끝으로 보냄
|
|
return objectToSpawn;
|
|
}
|
|
} |