- Home /
Instantiate random prefab ONCE
Hi!
I've got a simple wave system in place for my game and currently I have it so it spawns prefab 0 and goes up until it reaches the end. I would like it to spawn a random prefab of those. Then I would simply use "Random.Range". BUT I don't want it to spawn a prefab twice. I only want it to spawn it once. Like it spawns prefab 4. Then it never spawns that one. How could I do something like this?
Thanks in advance!
@alucardj Cute with the link. I'll take that in $$anonymous$$d next time I ask! But I honestly haven't tried anything. The reason is because I have no idea what I could use to accomplish this.
Answer by Imtiaj Ahmed · Feb 04, 2015 at 04:59 PM
You can consider using List. Not enough knowledge about it though, correct me anyone if the following codes need to improve. You can try this, worked for me-
using System.Collections.Generic;
.....
public List<GameObject> myList = new List<GameObject>();
.....
void Start () {
Debug.Log ("Total item now is " + myList.Count);
}
void Update () {
if(Input.GetKeyDown (KeyCode.Space)){
if(myList.Count == 0){
Debug.Log ("No Objects to spawn");
} else {
GameObject itemToSpawn = myList[Random.Range (0, myList.Count)];
GameObject myItem = Instantiate (itemToSpawn, transform.position, Quaternion.identity) as GameObject;
myList.Remove (itemToSpawn);
Debug.Log ("Total item now is " + myList.Count);
}
}
}
And populate the list in the inspector by dragging your prefabs to the list. Hope it helps somehow.
Answer by PrisVas · Feb 04, 2015 at 04:49 PM
You could make a list of the instanciated prefab, and then each Random.Range that you use to instanciate, you check if the list contains the chosen prefab. If its on the list, chose other, if not, instanciate.
Your answer

Follow this Question
Related Questions
spawn muzzle flash with random rotation? 2 Answers
Instantiate a random prefab at an objects location 3 Answers
Instantiating a random prefab from array. 1 Answer
How to instantiate prefabs between 2 objects like a path 0 Answers
Random instantiate at same frame with each instantiate having unique random direction 1 Answer