- Home /
Which AI finding enemy script is more efficient?
Hi everyone! So I'm trying to write an script to make an AI find an enemy constantly, but I'm doubting which script is more efficient:
1) Use a sphere collider and check onTriggerEnter, onTriggerStay, and onTriggerExit methods to know when to attack.
2) Use GameObject.FindGameObjectsWithTag("Enemy") to get al Enemies in the scene al later search which one is the closest to the AI. The problem is this method must be executed every frame with every AI in the secene and maybe is more inefficient than the Sphere Collider one.
So my question is, knowing there will be several AI in the secene, which script is more efficient?
Thanks!
there's only a few lines of code in each (maybe 3-6 lines of code)
try both, run them, and see if there is any difference in your specific situation.
Yes this is what I will finally do, but thought someone could have tested it before and let me know.
Answer by Ashkan_gc · Oct 13, 2012 at 01:22 PM
First of all, for the second method you can maintain a list of List and tell enemies to add themselves and remove themselves from it and eliminate the need for GameObject.Find Simple add yourself in Start and remove in OnDestroy in enemy script.
The performance depends on number of enemies, the number of other colliders in your scene and the amount of physics calculations in your game. Profiling as suggested is the best option but i think most of the times, trigger is the fastest option.
Finally I decided to rely on Unity's trigger implementation because as you said it is the fastest, but you've got a point with the list and the use of OnDestroy so if the performance decreases in the tests I will try this method. Thank you so much!