# Check distances of multiple objects, and do something if all outside of range

I've been trying to wrap my head around this for a bit now, and I can't quite figure out out. I'm trying to find the distance between all objects tagged Enemy and my player, and do something if all those Enemy objects are all outside a certain distance... This is as far as I've gotten:

``````var enemies = GameObject.FindGameObjectsWithTag ("Enemy");
for (var enemy in enemies){
var distanceToPlayer = Vector3.Distance(transform.position, enemy.transform.position);
if(distanceToPlayer >= effectiveDistance)
//this enemy is outside of the effective range;
}

``````

However, this only determines if each individual enemy is outside of the effective distance... I'm not entirely sure how to go about making it so I can figure out if ALL the enemy objects are outside of the effective range.

One way would be to use a Boolean 'enemy found in range' variable. Initialize it to false before the loop, then, if distanceToPlayer <= effectiveDistance for any enemy, set the variable to true. After the loop has executed, the value of the variable will tell you whether any enemy is in range of the player. (If all you're interested in is whether any enemy is within range of the player, you can terminate the loop at that point. If the test is performed in its own function, you can dispense with the Boolean variable and simply return 'true'.)

An optimization you can apply is to check the squared distance rather than the distance. Also, if the 'enemy' objects have colliders attached, you might be able to use the physics system's 'sphere query' function instead.

[Edit: Providing some additional clarification in case you're just not understanding my answer.]

In your original post, you stated that you wanted to determine if all enemies are outside of a specified range relative to the player. The solution I described above determines if any enemy is inside a specified range relative to the player. This is equivalent. It's like if you handed me a bunch of blocks and asked me to determine whether they're all red. I start looking through them one by one, and the moment I pick one up that's not red, I say, 'Done - they're not all red'. In other words, the existence of just one non-red block is sufficient to prove that not all the blocks are red. Similarly, the existence of one enemy that's in range is sufficient to prove that not all the enemies are out of range.

Does that make sense now? As for your comment below, the question you stated there is the opposite of the question stated in your original post, so perhaps you could clarify (via a comment or by editing your question) what it is that you're really wanting to know.

Hi there Jesse,

Would you care to elaborate on the sphere query function? Any example scripts on that matter?

thx B