- Home /
while loops infinitely, I can't tell why.
The way I expect this to work, is that the while loop will trigger this action, and if it makes it to the end with nothing happening, it should go through that same iteration again to roll a new random number to hopefully pass it's check this time, only THEN will i++ and proceed to the next iteration.
This works up until 2 of my targets have 0 health... then it starts looping infinitely and unity freezes... why? Shouldn't it just continue trying to roll "a" until "a" is a target with more than 0 health (as a side note, there are 6 targets, the infinite-looping begins after I've killed 2 of them usually...)?
void SelectFour ()
{
while (int i = 0; i < 4)
{
int a = Random.Range (0, 5);
if (targetHealth[a]> 0)
{
DoSomething();
i++;
}
}
}
You can't declare a variable in a while loop; it declares a new instance every time. $$anonymous$$ove the declaration outside.
so more like????:
void SelectFour ()
{
int i = 0;
while (i < 4)
{
int a = Random.Range (0, 5);
if (targetHealth[a]> 0)
{
DoSomething();
i++;
}
}
}
???
Answer by Uldeim · Nov 26, 2014 at 10:46 PM
While I can't speak to the exact problem, since the code for how targetHealth
is populated isn't there, I would suggest against using this approach, if possible.
The issue is that you have no control over how many times the loop will execute; you're hoping the random numbers eventually hit something that works, so this can theoretically never complete even in a mostly good case.
What I would recommend instead is to generate a collection of all possible valid targets, then generate a random number within the length of that set.
Something like (I'm guessing a lot about how things work):
List<BodyPart> validTargets = new List<BodyPart>();
for (int i = 0; i < bodyParts.Length; i++)
{
if (targetHealth[i] > 0)
validTargets.Add(bodyParts[i]);
}
if (validTargets.Count > 0)
{
for (int i = 0; i < 4; i++)
{
int a = Random.Range(0, validTargets.Count);
DoSomething(validTargets[a]);
}
}
I like where this is going, I'll have to try it out when I get home. I see that part of my problem has been that I have been trying to use arrays in a very dynamic way, but my life could be made simpler by using lists, problem there is I've never used lists before, I'll give this a go when I get home.
Your answer
Follow this Question
Related Questions
Unity crashes when using while 2 Answers
Breaking out of a loop 2 Answers
Help With "For Loop" Not Working? 2 Answers
Increment in while loop, with timeout 1 Answer
How to wait for Coroutine to finish? 2 Answers