I’ve built a function that allows me to generate an instance of a class, which is then added to a list and that list generates a series of buttons. At ‘midnight’ on ‘Sunday night’, I need it to generate six of these in a row ie. getting me six instances of the class, each of which will generate a button. But it’s not working.
It is perfectly fine if I only ask it to generate two instances, but when I put a third instance in, the editor freezes at ‘midnight’. I’ve checked it via generating through a button, and again it will allow the first two but not the third, even when there is a pause between commands. The same thing happens if there’s a combination of button and timed generation. Is there any reason that this would happen?
Edit 1: This is the part of my script that I think might be responsible (ie. the whole system works perfectly fine without it but when this is called as part of the class-generating function, the above happens).
Setting the variables at various points earlier in the script:
public static string[] agentstats = {"seduction", "sneakiness", "sniperskills", "deception", "combat"};
initialskillpoints = 70;
Actual function:
void CalculateAgentStats () {
print ("Calculating Stats");
string statname;
for (int i = 0; i < initialskillpoints; i++) {
statname = agentstats [Random.Range (0, agentstats.Length)];
switch (statname) {
case "seduction":
if (seduction == 20) {
i -= 1;
break;
}
else
{
seduction ++;
break;
}
case "sneakiness":
if (sneakiness == 20) {
i-= 1;
break;
}
else
{
sneakiness ++;
break;
}
case "sniperskills":
if (sniperskills == 20) {
i-= 1;
break;
}
else
{
sniperskills ++;
break;
}
case "deception":
if (deception == 20) {
i-= 1;
break;
} else
{
deception ++;
break;
}
case "combat":
if (combat == 20) {
i-= 1;
break;
}
else
{
combat ++;
break;
}
}
}
}
Edit 2:
So, a bit more work debugging/crashing Unity found me the problem but I don’t know how to fix it. The problem is the “i -= 1” line. I think it’s causing a potential infinite loop because if you had epically bad luck with your randomization, you could get caught in a i++, i-=1 circle. But the odds of that (first getting to 20, and then forever randomly choosing that same stat) are so low that I can’t see why Unity would object to it.
Can anyone explain this, and tell me how I could get this same functionality to work (ie. if a stat has already reached 20, it can’t go any higher and the loop needs to go again).