- Home /
Pooling Issue
Hey there!
I have recently used a simple forloop to instantiate a world on runtime. It was working perfectly without lag or anything on my phone and computer.
However I wish to optimize it some more and I instantly got brought in to the world of object pooling. So I created a simple script that Instantiates in front of the player as he moves and removes the ones that are far behind.
This is where I started pooling them instead of using Destroy. Now everything seemed to work fine as I tested pooling.
The objects get deactivated instead of destroyed behind me, they get put into a GameObject List. And reactivated in front where the new one is supposed to be.
However after a couple of seconds in to the game. It just stops. But thats not the whole deal here because they do get activated in front of the player still, but only for a split second. Then it deactivates itself again immediately.
They remain pooled for some reason. I tried writing it myself, i tried other peoples scripts and I came to the conclusion that this one worked the best. But I still get the deactivation problem. Here it is:
public GameObject[] platformPrefabs;
public bool willGrow = true;
WorldGenerator generator;
public List<GameObject>[] pooledObjects;
void Start()
{
generator = GameObject.Find("World GENERATOR").GetComponent<WorldGenerator>();
platformPrefabs = generator.WorldObjects;
/*for (int i = 0; i < generator.WorldObjects.Length; i++)
{
platformPrefabs[i] = generator.WorldObjects[i];
}*/
// instantiate our pool (empty)
pooledObjects = new List<GameObject>[platformPrefabs.Length];
for (int i = 0; i < platformPrefabs.Length; i++)
{
pooledObjects[i] = new List<GameObject>();
}
}
public GameObject GetPooledObject()
{
int randomIndex = Random.Range(0, pooledObjects.Length);
for (int i = 0; i < pooledObjects[randomIndex].Count; i++)
{
GameObject go = pooledObjects[randomIndex][i];
if (!go.activeInHierarchy)
{
return go;
}
}
if (willGrow)
{
GameObject obj = (GameObject)Instantiate(platformPrefabs[randomIndex]);
pooledObjects[randomIndex].Add(obj);
return obj;
}
return null;
}
Thanks for the help!
EDIT
Here's what I use to get the object in another script:
GameObject newObject = theObjectPool.GetPooledObject();
newObject.transform.position = transform.position;
newObject.transform.rotation = transform.rotation;
newObject.SetActive(true);