Untitled
unknown
plain_text
2 years ago
1.7 kB
9
Indexable
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPooler : MonoBehaviour
{
[System.Serializable]
public class Pool
{
public string tag;
public GameObject prefab;
public int size;
}
#region Singleton
public static ObjectPooler instance;
private void Awake()
{
instance = this;
}
#endregion
public List<Pool> pools;
public Dictionary<string, Queue<GameObject>> poolDictionary;
void Start()
{
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);
}
}
public GameObject SpawnFromPool(string tag, Vector2 position)
{
if (!poolDictionary.ContainsKey(tag))
{
Debug.LogWarning(tag + " Doesnt exist");
Debug.Log("TAG:" + tag);
return null;
}
Debug.Log("TAG:" + tag);
GameObject objectToSpawn = poolDictionary[tag].Dequeue();
objectToSpawn.transform.position = position;
objectToSpawn.transform.rotation = Quaternion.identity;
objectToSpawn.SetActive(true);
poolDictionary[tag].Enqueue(objectToSpawn);
return objectToSpawn;
}
}
Editor is loading...
Leave a Comment