Hi
I have the this object pooling script in my game that works just fine. But every time I reload my project I have to remove the script from the respective game object just to readd it and set all the parameters again. Does anyone know what the problem could be?
The script:
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 Dictionary<string, Queue<GameObject>> poolDictionary = new Dictionary<string, Queue<GameObject>>();
public List<Pool> pools;
// Start is called before the first frame update
void Start()
{
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, Vector3 position, Quaternion rotation)
{
if (poolDictionary.ContainsKey(tag))
{
GameObject objectToSpawn = poolDictionary[tag].Dequeue();
objectToSpawn.transform.position = position;
objectToSpawn.transform.rotation = rotation;
objectToSpawn.SetActive(true);
poolDictionary[tag].Enqueue(objectToSpawn);
return objectToSpawn;
}
else
{
Debug.Log("Pool with tag " + tag + " doesn't exist.");
return null;
}
}
}