Nearest Enemy To Team (Without Crowding!)

Hi all,

I have a script to assign the nearest enemy to each of my 3 team players. However I do not want team members to crowd to the same enemies.

They should distribute themselves evenly otherwise they will get picked off as they all focus on one enemy.

I can run the find nearest script multiple times and each asking the team players to ignore an enemy character that is closer to another team-mate. However this seems like a very heavy process to run each frame.

Any suggestions, is there a better way to do this?


You can assume that if the code responsible for saying “this ones already taken” executes prior to the next sweep. So unless you’re pausing during that sweep operation, you are correct.

Consider creating a large trigger attached to your seeker objects. The objects found during OnTriggerStay(){} are the objects in the seeker’s vicinity. You can query those objects for whatever - name, tag, layer, script - and use that to make decisions. This is a decentralized approach to management.

Sometimes it makes more sense to track objects and compare the objects to one another without using triggers. This implies you have some kind of all-seeing script tracking (keeping references to) all your agents. By looping over groups of agents, you can make decisions and apply logic to them. This is a centralized management style.

You should use both interchangeably (they compliment each other) based on which makes more sense in a given case, but I like having an all-seeing script in any project. (In practice it’s usually many scripts with a common point of access like a singleton “parent”).

Using Finds() every frame is really never a good idea. They are the weakest possible approach to reference management. You might get away with it on small test projects, but it should not be treated as a primary tool for tracking references.

Simple decisions like this are okay without using a service, but eventually you may want more complex “group decisions” - these can be handled by making requests to a service which can examine the situation based on data passed in by group members.