- Home /
Question by
HellYeahUpperCase · Mar 08, 2018 at 08:42 PM ·
c#spawninglistsrandom.range
Spawning random prefabs at random spawn points (C#)
Ok I'm trying to do 2 things :
1- Once a prefab is spawned, it should not spawn a second time
2- Once a spawn point is used for a prefab, it should not be used a second time (so two objects don't spawn at the same location)
Been trying to do this with lists. The problem I have is with removing the right items in the lists in a while loop, it seems to be problematic. The objects all spawn at the same spawn point and I don't know why.
Anyone know how to do this?
Code:
public List<GameObject> myList = new List<GameObject>();
public List<GameObject> spawnPoint = new List<GameObject>();
void Start () {
Debug.Log ("Total objects to spawn now is " + myList.Count);
if(myList.Count == 0){
Debug.Log ("No Objects to spawn");
} else {
if(spawnPoint.Count ==0)
{
Debug.Log ("No more spawn points");
} else {
while (myList.Count > 0) {
GameObject itemToSpawn = myList [Random.Range (0, myList.Count)];
GameObject spawns = spawnPoint [Random.Range (0, spawnPoint.Count)];
Vector3 position = GameObject.FindGameObjectWithTag ("replace").transform.position;
GameObject myItem = Instantiate (itemToSpawn, position, Quaternion.identity) as GameObject;
myList.Remove (itemToSpawn);
Debug.Log ("Total item now is " + myList.Count);
spawnPoint.Remove (spawns);
Debug.Log ("Total spawn points now is " + spawnPoint.Count);
DestroyObject (GameObject.FindGameObjectWithTag ("replace"));
}
}
}
}
}
Comment