- Home /
get closest enemy
hey, how do I get a list of all the gameObjects in my scene with the name 'enemy' and then which one is the closest to the object with this script attached to it. thanks
Answer by Bampf · Aug 25, 2010 at 11:31 AM
Rather than find ones with the name Enemy on them, you should either search for objects with a particular script on them, or for objects with a particular tag on them.
I recommend tags, because it's probably much faster, and an example of finding the closest enemy is actually given in the manual entry for FindGameObjectsWithTag. The function you want is FindClosestEnemy. A minor change I'd make: in the example, I see they are calculating distance with two lines of code:
var diff = (go.transform.position - position);
var curDistance = diff.sqrMagnitude;
This can be replaced with one line:
var curDistance = Vector3.Distance(go.transform.position - position);
If you need to find the closest enemy often, an alternative might be to put a big spherical collider (set to be a trigger) on the object. Then (assuming the enemies have colliders on them) you will get notified as soon as an enemy moves into range.
I'm trying to make a tower defense game, so how would I do the collider trigger one?
Well the manual has info on Triggers, and there are other answers posted about collision detection in general. It wouldn't be hard to detect when the first enemy moves into range, using triggers. However, once that enemy is dead the tower needs to find another enemy, typically the one closest to the player's base. So you'd probably be better off using tags for that case, not triggers.
I think you mean "Vector3.Distance(go.transform.position, position)". Actually using the sqr$$anonymous$$agnitude is a better choice because calculating the distance squared less computationally expensive than calculating the distance. (It has one less square root.)
Your answer
Follow this Question
Related Questions
Randomizate bullets help 2 Answers
I need some health with my health/enemy script 0 Answers
Restart this script 3 Answers