Im assuming each AI has itās own loop.
Try having one master controller script that controls ALL AI. Also, try making a āschedulerā of sorts. Perhaps the more distant they are, the less the AI updates or something. That way, closest AI would be the most responsive.
You would also benefit from making the AI āsleepā when it doesnāt need to do anything; i.e not processing that AI at all if itās just standing there. Only process whatās needed. Processing one at a time in this fashion would yield the best performance gain, provided each AI can wait 0.03
seconds between the other. 0.03 * 100 = 30
seconds for all AI to process one task cycle, thatās no good. Try to make it so each AI is processed every 1 second if its not marked āasleepā (see below). In this case, we would have to do 3 AI task cycles per wait()
to keep all 100 AI doing something every 1 second, which is still a lot better than each of them doing it every wait()
, in fact itās exactly 33.333x more efficient in this particular example.
For calculating distances, calculate the distances for all AI and put them into a table, do this once per loop on the master controller. You can then use the distance to judge whether you want them to sleep/wake up, delay their next action for X cycles, something like that. The more distant the AI is, the less often you can check its magnitude for even better performance, then every AI doesnāt need to check magnitude every task cycle.
The idea here is for one, cutting down on the number of threads with loops, and two, cutting down on the number of things your doing with these AI per loop cycle.
Also, any constant variables, store them outside of the loop, including functions i.e math.random
Itās much faster if you have them pre-stored like so:
local workspace = game:GetService"Workspace"
local dummies = workspace:WaitForChild"Dummies"
local random = math.random
... etc
Also, if you use the same thing more than once inside the loop, make sure you that is a variable too. i.e:
while true do
local t = os.time()
end
instead of spamming os.time() many times. Same goes for magnitude checks, health checks, anything of the sort. Check it once, store the result, keep on processing the data.
These are all good places to start. Lmk if I did a poor job explaining and Iāll clear it up for you, Iāve ran hundreds of AI in this manor, if you schedule them right, take advantage of putting AI you cant see to sleep, and the other methods described, itās a night and day difference in performance.