Question by
terpfiend · Apr 08, 2016 at 06:29 AM ·
scripting problemspawnspawning problemsobject poolspawner
question about object pooling an array and spawning
Hey guys, first time posting here so I hope it's all formatted correctly. So right now i'm trying to make a simple frogger game in which the cars are stored in a pool of objects and spawned randomly.
The problem I'm facing is that the first couple cars to be spawned are always the same. It'll usually do 3-5 of the same car in a row and then begin randomizing them (there are 23 in total).
Here are my Object Pooler and Car Spawning scripts:
Object Pooler:
using System.Collections.Generic;
public class ObjectPoolerScript : MonoBehaviour {
public static ObjectPoolerScript current;
public GameObject[] pooledObject;
public int pooledAmount = 20;
List<GameObject> pooledObjects;
void Awake()
{
current = this;
}
void Start ()
{
int randomIndex = Random.Range(0, pooledObject.Length);
pooledObjects = new List<GameObject>();
for (int i = 0; i < pooledAmount; i++)
{
GameObject obj = (GameObject)Instantiate(pooledObject[randomIndex]);
obj.transform.parent = transform;
obj.SetActive(false);
obj.SetActive(false);
pooledObjects.Add(obj);
}
}
public GameObject GetPooledObject()
{
int randomIndex = Random.Range(0, pooledObject.Length);
if (pooledObjects.Count == 0)
{
GameObject obj = (GameObject)Instantiate(pooledObject[randomIndex]);
obj.transform.parent = transform;
obj.SetActive(false);
obj.SetActive(false);
pooledObjects.Add(obj);
}
// Get a reference to the first gameobject in the pool.
GameObject ret = pooledObjects[0];
// Remove that gameobject from the pool list.
pooledObjects.RemoveAt(0);
// Activate the instance.
ret.SetActive(true);
// Put it in the root of the hierarchy.
ret.transform.parent = null;
// Return the unpooled instance.
return ret;
}
}
Car Spawner:
using System.Collections.Generic;
public class CarFireScript : MonoBehaviour {
public float fireTime = 1f;
void Start ()
{
InvokeRepeating("Fire", fireTime, fireTime);
}
// Update is called once per frame
void Fire ()
{
GameObject obj = ObjectPoolerScript.current.GetPooledObject();
if (obj == null) return;
obj.transform.position = transform.position;
obj.transform.rotation = transform.rotation;
obj.SetActive(true);
}
}
In my inspector I have been messing with the Pooled Amount, but have it at 10 for now. I've noticed the larger the number the more often repeats are spawned.
Anyone have some suggestions? I'd appreciate any help.
Comment