I’m currently working at script attached to player’s units that detects nearby enemy’s units when they are close to let them auto-attack eachother. And I wonder what is better for performance.
I’ve made IEnumerator that waits for const X time to refresh nerby units, select closest one and attack if it’s in idle state.
But there’s another option. I can attach collider to each unit and script that detects enter of enemy’s collider and then it may choose best target.
So there comes a question, what’s better for performance?
How often collider updates function “OnEnter” to check if any collider has enter, compared to IEnumerator that waits for time and then starts refresh?
Well, for performance the IEnumerator and Physics.OverlapSphereNonAlloc is probably the best approach. OnTriggerEnter will be called everytime when another collider enters the trigger. Since you usually want your units to stick to a certain target either for a certain amount of time or until the current target leaves a certain radius, with a coroutine can can completely ignore detecting other enemies until necessary. If you have many enemies and many friendly units there would be countless of OnTrigger callbacks, especially if you have a rather large detection radius.
How to do the actual target selction highly depends on what behaviour you need / want. I know some tower defence games where you can select from various targeting modes (closest, furthest, newest, oldest, weakest, strongest, fastest, slowest) and in addition to those you can toggle “lock on target”. Though the towers had zero reaction / aiming time. So there was no issue if they switch between different targets rapidly. However if your aiming takes some time, switching rapidly would probably result in never actually attacking anyone if the “best” target changes often.
OnTriggerEnter might seem to be useful as you could evaluate the new enemy that just got in range the moment it enters. However in order to make a decision which target to choose you would need to keep track of all enemies that has previously entered the range. So you would need some sort of housekeeping. “OverlapSphereNonAlloc” will get you a list of all enemies in range but without all those callbacks (OnTriggerEnter / OnTriggerExit).
Even when you have a quick changing targetmode, collecting the enemies in range just every third or fourth frame would probably be enough. For lock on behaviour you can omit the searching completely until the current enemy is dead or out of range.