How can I make my random switch statement not select the same object twice in a row
I have 3 buttons if 1 is pressed it will get turned off and another one will randomly be selected and turned on, this works but i don't want the same button to be turned on in a row how do i do this? this is the script i used:
void Update () { if(loop == true) { Invoke ("random", 0f); loop = false; } }
void random ()
{
index = Random.Range (0, buttons.Length);
switch (index)
{
case 0:
BS.button1 = true;
break;
case 1:
BS.button2 = true;
break;
case 2:
BS.button3 = true;
break;
}
}
Answer by Baste · Oct 02, 2015 at 02:36 PM
hacky, fast solution:
private int lastIndex = -1;
void Random() {
int index;
do {
index = Random.Range(0, buttons.Length);
while(index == lastIndex);
lastIndex = index;
//as before
}
Note that this will cause an infinite loop if there's only one button, as it's impossible to not pick the same button as the last time if there's only one. Consider including a work-around for that if there's times where you'll only have one button.
Good luck! Have fun making games!
Perfect, this worked exactly how I want it too ^^ Thanks a lot!
Your answer
Follow this Question
Related Questions
Random.Range returns either 1 or 2 2 Answers
Creating an Array that can be accessed by a Random.Range c# 1 Answer
Script is not getting a reference. 1 Answer
Choose Waypoints from a Random Array of Paths 0 Answers
local scale not working? 2 Answers