Instantiating prefabs randomly from an Object Pool

Hi all,

I currently have a script that works pretty well for randomly spawning prefabs and then deactivating them and repeating the process. Although using the current process my game still suffers from instantiation stuttering and subtle lag spikes.

public class ObjectPool : MonoBehaviour {

		public GameObject[] forestPrefabs;

		public bool willGrow = true;
		
		public List<GameObject>[] pooledObjectsForest;
		
		void Start()
		{
			// Instantiate our pools
			pooledObjectsForest = new List<GameObject>[forestPrefabs.Length];
		

			for (int i = 0; i < forestPrefabs.Length; i++)
			{
				pooledObjectsForest *= new List<GameObject>();*
  •  	}*
    
  •  }*
    
  •  public GameObject GetPooledObjectForest()*
    
  •  {*
    
  •  	int randomIndex = Random.Range(0, pooledObjectsForest.Length);*
    
  •  	for (int i = 0; i < pooledObjectsForest[randomIndex].Count; i++)*
    
  •  	{*
    

_ GameObject go = pooledObjectsForest[randomIndex];_

* if (!go.activeInHierarchy)*
* {*
* return go;*
* }*
* }*

* if (willGrow)*
* {*
* GameObject obj = (GameObject)Instantiate(forestPrefabs[randomIndex]);*
* pooledObjectsForest[randomIndex].Add(obj);*
* return obj;*
* }*

* return null;*
* }*
}
Is it possible to instantiate all the prefabs within my Array “forestPrefabs” at run time and then randomly select prefabs from that list?
Any help will be greatly appreciated,
Thanks,
Takz

I’m not too experienced with C# or object pooling, but I think I see a problem with your code.

Your are setting the randomIndex variable at the start of your GetPooledObjectForest, so when your for loop gets run, and the object and index randomIndex is already active, then it won’t do anything. Then it will increment i, loop again, try to get the same exact object, and fail again. And it will continue to do so until either the object becomes inactive, or i >= randomIndex.

Besides that, you might have to many objects pooled at once which might cause the lagginess. Object pooling helps with the processing, but it can still eat away at the Memory if you have too many objects.