- Home /
Checking Enemies In An Area.
Okay, I have a bunch of different sections scattered around the map. In these sections only so many enemies can be in at one time. How could I check which enemies are in the section. This would later be used to spawn/upgrade enemies.
Thanks, Thor
Answer by robertbu · Jun 19, 2013 at 03:43 AM
Assuming you can define an area as a circle/sphere, one easy way would be to use Physics.OverlapSphere(). Another way would be to setup a collider that encompassed the area and set it to a trigger. you could keep track of enemies with OnTriggerEnter() and OnTriggerExit(). Or you could define your areas using Rects, get a list of all enemies based on tag, and then test if their XZ position was within each of the Rects.
This is what I have got so far:
var hitColliders : Collider[] = Physics.OverlapSphere (transform.position, radiusCircle);
for (var hit : Collider in hitColliders) {
if(hit.gameObject.tag == "$$anonymous$$illable"){
// Enemies
}
}
How would I put all of those in an array (var Enemies:GameObject[]) so I can access each one.
Your answer is greatly appreciated by the way.
I would suggest using a generic list rather than a built-in array. Generic lists can grow dynamically rather than be a fixed size.
At the top of the file add:
import System.Collections.Generic;
var enemies : List.<GameObject> = new List.<GameObject>();
And then in your for loop:
enemies.Add(hit.gameObject);
$$anonymous$$ore info on generic lists:
This is very helpful, but how do I find the length of the list?
Actually never$$anonymous$$d the last question: it is enemies.Count.
If you question is answered, please click on the checkmark nextto the answer to close it out. Thanks.
Your answer
Follow this Question
Related Questions
Help with Enemy AI 1 Answer
AI controller script, Enemy movement issues 0 Answers
Problem with the movement of AI 1 Answer
Collsions problem 0 Answers
Rotating on X and Z axis only 2 Answers