- Home /
Duplicate Question
instantiate objects randomly and unique to fixed positions
I am creating a game where there are 3 positions p1,p2,p3 and there are 3 objects, b1,b2,b3. Now When game opens I want to assign each object a unique random position. so if b1 takes position p2, then b2 should take p1 or p3. if b2 takes p3 then b3 should take p1. I am totally confused. I can assign random positions to objects but I am not sure how to make it unique, so the next object should not take the position which is already taken.
So basically in the game, user is presented with the 3 boxes. And one of them is a bad box but all boxes look same. I want to assign that bad box a random position always. so if user clicks bad box game is over, if user clicks other boxes he goes to the next level and again 3 boxes comes with bad box in one of the three positions
Please help me with this
Thanks in advance
1) Put either your objects or your positions in an array and shuffle the array. Shuffle code has been posted to Unity Answers and Unity Forums several times, and you will find versions of it numerous places on the web. After shuffling, assign in order. 2) Put either your objects or your position in a generic List. Pick from the list randomly and then assign, deleting the entry after use.
Note for a three entry array, you can shuffle by:
var i = Random.Range(0, 3);
if (i != 0) {
var t = theArray[0];
theArray[0] = theArray[i];
theArray[i] = t;
}
i = Random.Range(1,3);
if (i != 1) {
t = theArray[1];
theArray[1]= theArray[i];
theArray[i] = t;
}