Hi,
Sorry if my question seems weird. I’m quite new to coding and game development.
My first game includes a bunch of different objects which create and after a while destroy. As I heard instantiating and destroying objects constantly is so expensive so I used pooling for my objects and now I totally stuck
In my game, if the user clicks the objects before 4 seconds it will be returned to the pool and if the player misses the click after 4 seconds it will be returned to the pool either but it should decrease one HP.
So before pooling, I’d used the timer on each of my game objects that damaged health, and in my click manager, I used destroy method so the HP system automatically worked.
But now as the object doesn’t destroy and is just disabled I don’t know how to fix it.
Are there any ways to use interfaces to fix it? For example, if I want to check bool (isActive
) for each object that spawns from pool in 4 seconds.
My pool script:
using System.Collections.Generic;
using UnityEngine;
public class ObjectPooler: MonoBehaviour
{
[System.Serializable]
public class Pool
{
public string tag;
public GameObject Object;
public int size;
}
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.Object);
obj.SetActive(false);
objectPool.Enqueue(obj);
}
poolDictionary.Add(pool.tag, objectPool);
}
}
public GameObject SpawnFromPool(string tag, Vector2 position, Quaternion rotation)
{
if (!poolDictionary.ContainsKey(tag))
{
Debug.LogWarning("Pool with tag" + tag + "doesn't exist.");
return null;
}
GameObject objectToSpawn = poolDictionary[tag].Dequeue();
objectToSpawn.SetActive(true);
objectToSpawn.transform.position = position;
objectToSpawn.transform.rotation = rotation;
poolDictionary[tag].Enqueue(objectToSpawn);
return objectToSpawn;
}
public GameObject ReturnObjectToPool(string tag, GameObject returnObject)
{
poolDictionary[tag].Enqueue(returnObject);
returnObject.SetActive(false);
return returnObject;
}
}