AI Optimization

Hi to all

There has been something on my mind for a while now , what would be better.
When I have an AI script for lets say enemies , that does the distance raycast calculation and the movement and I
a. Assign it to each individual enemy
b. Have a game engine script that basically does the same but on the update command loop through each enemy in an array and does the required updates ?

My common sense would point me to option b as there would be far less declarations of the AI script but heres the thing , what if the AI enemies become a huge amount , would the thread it runs on be slowed down as apposed to when each enemy gets their own behavior script and each run on their own thread ?

The best way is to test.

I would also think answer b gives better optimization as you only get one Update call and it runs a for loop which is no issue.

As for your concern on would it slow down the thread, the only difference is that instead of doing the same thing in many places it does it many times in the same place.

Again, you would have to test since when running on the script you get direct access to the members while running on a separate script you need a dereferenciation which is no big deal though.

Your idea of less script and better memory management is wrong. You would save the Update method but the variables should still be in separate scripts. Or it means you have a large array or list but then you still use pretty much the same amount (you would save the overhead of the object).

Finally, if you think this will run slow when too many guys are in, you can minimize the amount of computation using a timer or InvokeRepeating. This way you can get your Update to run only at specific frequency.

void Start){
   // First update after 0.05s and every 0.5s 

void UpdateMethod(){
   // Here is the update

You can also cut your AI using coroutines so that you do some computation for a certain time and come back next frame to finish it off.

Well its what you prefer really - I prefer my NPCs to be autonomous and have their own scripts. The instance of the script is effectively just the size of the variables that define its current state (plus a small overhead) and so it will make no material difference.

Next there are no threads for this in Unity. You can have your AI run on a separate thread if you write it that way (see but it has to not interact with any scene objects at the time, so raycasting is out.

Your best bet is to use coroutines and yield to have AI run across several frames - so you should separate your movement from your decision making allowing the movement every frame but the decision making to be spread. This will allow you to have much more intelligence by (for example) using more raycasts as feelers around dynamic obstacles etc.