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++;
		}
	}
}

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 *> 0)*

validTargets.Add(bodyParts*);*
}

if (validTargets.Count > 0)
{
for (int i = 0; i < 4; i++)
{
int a = Random.Range(0, validTargets.Count);
DoSomething(validTargets[a]);
}
}