What is the optimal way to handle the AI of enemies?

Currently, in my game, a number of enemies are spawned. Their AI is currently being handled through a while loop, in each, where they wait a little, based off the environment choose an action and then perform it. They are all performed at the same time through the use of task.defer.

I was wondering how to optimize this process. Should I keep it as it is but apply parallel lua? Perhaps have a Heartbeat event iterate through each NPC, check if it can perform an action, and if it can, spawn it? I am open to suggestions and to discuss the issue, thanks!

3 Likes

Since Roblox’s environment is asynchronous you could take advantage of it to make their scripts run for themselves and it would bring more realism than just seeing bunch of AI always update at the same time. (You can also use RunService.Stepped instead, which will update at every step of the server instead of a while loop which is less effective since it’s not directly a branch of the RunService).

Astoforce people wrote a pretty solid devforum post about this:

3 Likes

Regarding this point, how does it compare? At the moment my NPC has a while loop that yields before each iteration to finish doing the attack. If I changed it to a RunService event that would check if it is performing a move or not, how would it compare performance wise?

Just read the post, thanks for sharing!

Although it doesn’t quite dwelve into the issue at hand. For once, I did notice this short:

This perhaps would count as a clue as to not have such events handle too much code upon signaling. Perhaps the method I suggested of waiting for Heartbeat and checking if each enemy could run is indeed faulty. That leaves me with the option to use Parallel Lua and have multiple while loops running?

1 Like

use a runservice.heartbeat event and loop through a table of enemies… include path and target data etc in the tables, and then maybe have a navpath for all enemies to follow and update the path every time heartbeat fires (you can add a cooldown too)