I wrote an object pooling script that’s supposed to set active a random prefab from an object pool active every time the camera moves some random distance to the right. So far, all it does is Instantiate and set the prefabs inactive on awake. I can’t get it to reference or set active anything from the list, and I’m not sure what else to try. I’ve tried multiple things from multiple sources, including the Unity - Scripting API: ObjectPool (unity3d.com), but most object pooling examples online are something like “pool exactly 20 identical bullets” and it’s hard to find something like “spawn random prefab from pool”. I would appreciate any feedback/help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Pool;
public class EOMovement : MonoBehaviour
{
//camera distance vars
private int spawnDistanceGoal;
private int randomStepNumber;
//object pooling vars
private int randomListObject;
public static ObjectPool<GameObject> SharedInstance;
public List<GameObject> allObjectPool;
public int randomObjectPoolNumber;
public GameObject currentObjectInPool;
void Awake()
{
for(int i = 0; i < allObjectPool.Count; i++)
{
currentObjectInPool = Instantiate(allObjectPool[i]);
currentObjectInPool.SetActive(false);
}
}
void Start()
{
randomStepNumber = Random.Range(1, 7);
spawnDistanceGoal = (DistanceTravledDisplay.distanceTravled + randomStepNumber);
StartCoroutine(Spawn());
}
private IEnumerator Spawn()
{
if (DistanceTravledDisplay.distanceTravled >= spawnDistanceGoal)
{
Debug.Log("Something should spawn now!");
randomObjectPoolNumber = Random.Range(0, allObjectPool.Count);
currentObjectInPool = (allObjectPool[randomObjectPoolNumber]);
currentObjectInPool.SetActive(true);
//Pooling and Instantiation code would probably go here
yield return new WaitForSeconds(2);
randomStepNumber = Random.Range(1, 7);
spawnDistanceGoal = (DistanceTravledDisplay.distanceTravled + randomStepNumber);
StartCoroutine(Spawn());
}
else
{
yield return new WaitForSeconds(2);
StartCoroutine(Spawn());
}
}
}