The question is answered, right answer was accepted
Potential infinite while loop?
This code assigns each of the four players a secret role, as well as three fake roles. However, sometimes I click play, and the scene does not open. The play button is still grey, but it will not turn blue to load the scene. I looked it up and the main answer I got was that it could be an infinite while loop. Below is my code which occurs in the start function.
p1_role = Random.Range(1, 10);
p2_role = Random.Range(1, 10);
p3_role = Random.Range(1, 10);
p4_role = Random.Range(1, 10);
// prevent repeats of roles
while (p2_role == p1_role)
{
p2_role = Random.Range(1, 10);
}
while (p3_role == p1_role || p3_role == p2_role)
{
p3_role = Random.Range(1, 10);
}
while (p4_role == p1_role || p4_role == p2_role || p4_role == p3_role)
{
p4_role = Random.Range(1, 10);
}
The code also assigns three fake roles per player, that must not match the real role:
p1_fake_role_1 = Random.Range(1, 10);
while (p1_fake_role_1 == p1_role)
{
p1_fake_role_1 = Random.Range(1, 10);
}
p1_fake_role_2 = Random.Range(1, 10);
while (p1_fake_role_2 == p1_fake_role_1 || p1_fake_role_2 == p1_role)
{
p1_fake_role_1 = Random.Range(1, 10);
}
p1_fake_role_3 = Random.Range(1, 10);
while (p1_fake_role_3 == p1_fake_role_2 || p1_fake_role_3 == p1_fake_role_1 || p1_fake_role_3 == p1_role)
{
p1_fake_role_3 = Random.Range(1, 10);
}
This fake role assigning is repeated for each player. The strange thing is, the scene runs totally fine sometimes, but other times it won't open, as I described above.
Big thanks in advance for any help!
there's a simpler approach to this problem.
create a list with all of the possible roles then create a method to assign roles from that list. after assigning a role, remove it from the list of available roles. that way you will never assign the same role to another player and you won't need those messy while
statements...
Answer by Bonfire-Boy · Sep 21, 2016 at 09:08 PM
Yes, it's an infinite loop. On line 9 of the second script you assign to p1_fake_role_1
instead of p1_fake_role_2
. So sometimes it'll get trapped there.
But gjf is right, there are much better ways to do this. You're creating a lot of work for yourself with this approach - not only in the coding (so much code to add every time you change your set of roles) but also because you're much more likely to end up with bugs.
Think of your set of roles like a pack of cards. Put them in a list, shuffle it, then just pop them from the list as required.
Oh god, you're right...I can't believe I missed that. Thanks! I'm trying out using lists ins$$anonymous$$d as well, and it seems to be working.