- Home /
How To NOT Instantiate the same Prefab Twice (C#)
Hello, I have 5 prefabs (5 different colors[blue,red,pink,yellow,green]) and every 10 seconds My Game Instatiate one of those randomly, for the next 10 seconds. Because is Randomly generated, sometimes it generates the same color after the 10 seconds. For example: Generates Blue the first 10 seconds and generates Blue again for the next 10 seconds.
How do I Randomly Generate my prefabs without Generating the same prefab twice in row?.
Thank You.
This has already been asked.
If all you want is for the prefab to be different from the last prefab then do it til it isn't.
eg
GameObject[] prefabs;
GameObject lastPrefab=null;
GameObject nextPrefab;
do {
nextPrefab=prefabs[Random.Range(0,3)];
} while (nextPrefab=lastPrefab);
lastPrefab=nextPreafb
If what you really want is the four prefabs each once, in random order then see this
http://answers.unity3d.com/questions/252884/shuffle-objects-in-object-array-randomly-in-c.html
Answer by Nemonocerater · May 17, 2014 at 12:30 AM
You could make an enum { blue, red, ... } and keep track of the last one that it picked, then randomly pick a new one after 10 seconds. If the new one is the same color as the last one, then randomly pick again.
If is the same color as the last one, how do I randomly pick again?
How ever you randomly picked your first one just do it again, and keep doing it until you get a prefab that wasn't the one you picked last time. I would do the same thing as Jeff except have them as enums. Does that answer your question?
Your answer
![](https://koobas.hobune.stream/wayback/20220613145220im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Can't set the random position for an Instance. 1 Answer
instantiating vertically 2 Answers
instantiate random prefabs based on player camera distance 1 Answer
Problem with prefab parent and children objects that need to be instantiated multiple times. 1 Answer
Prefab doesn't hold prefab of itself, Instead just copies itself on Instantiate() 1 Answer