need help in making an object pooler
im making an unity2d game and need an object pooler to generate the ground. however in this version, instead of generating the ground sprites individually, i need to generate groups of them randomly arranged in prefabricated layouts. The pooler i have only generates them individually
public GameObject pooledObject;
public int pooledamnt;
List<GameObject> pooledObjects;
// Start is called before the first frame update
void Start()
{
pooledObjects = new List<GameObject>();
for (int i = 0; i < pooledamnt; i++)
{
GameObject obj = (GameObject)Instantiate(pooledObject);
obj.SetActive(false);
pooledObjects.Add(obj);
}
}
public GameObject GetPooledObject()
{
for (int i = 0; i < pooledObjects.Count; i++)
{
if (pooledObjects[i].activeInHierarchy)
{
return pooledObjects[i];
}
}
GameObject obj = (GameObject)Instantiate(pooledObject);
obj.SetActive(false);
pooledObjects.Add(obj);
return obj;
}
// Update is called once per frame
void Update()
{
}
}
all help appreciated
Answer by streeetwalker · Sep 22, 2020 at 11:22 AM
It looks like you have a conceptual problem with the Object Pool pattern. I'll address that after your main point:
If you need to grab more than one object from the pool, grab more than one - as many as you need to arrange your ground "tiles".
The problem you have is you are defeating the purpose of the pool:
1. In Start you instantiate all the objects you will need to populate the pool.
2. But in GetPooledObject you do not grab an object from the pool. Instead you instante the object all over again, and then add it to the pool again. Your pool will just grow and grow.
In concept, when you need to Grab an object, you should be remove it from the pool until such time that you are done with it, when you will put it back in the pool.
The implementation is a bit more involved and you should go through some of the many Object Pool tutorials on youTube.