Events vs while loop

While Loops for enemy AI’s or Event Loops?
What do I mean or what is this post for?
I’m here to gather your opinion on whether you should use a while loop or an event loop and which is more efficient.

For example

  1. A While loop for 2 NPCS
local function getEnemy()
    local enemy = nil;
    for i,v in next, workspace.Live:GetChildren() do
       if math.random(1,3) ~= 2 then continue end;
       if game.Players:GetPlayerFromCharacter(v) then continue end;
       enemy = v
       break
    end
end;
task.spawn(function() -- Inside Enemy 1
   while task.wait() do
       getEnemy()
   end
end)
task.spawn(function() -- Inside Enemy 2
   while task.wait() do
       getEnemy()
   end
end)

OR
2) Event That Does this at Once

while task.wait() do -- A script that loops in live and fires enemy controllers
    for i,v in next, workspace.Live:GetChildren() do
        if not v:FindFirstChild('EnemyController') then continue end;
        v.EnemyController:Fire('Awake'); -- Fires GetEnemy()
    end;
end;

Just to inform, these are just snippet codes I wrote on roblox dev forum to reflect my point. (Manual space indentation)

also which will take more fps?

For better performance and scalability, the event loop that handles all NPCs in one go is generally more efficient, particularly in experiences with a large number of NPCs. It reduces the overhead associated with multiple concurrent tasks and centralizes the logic, making it easier to manage and optimize.

However, if individual NPC behavior and responsiveness are critical and the number of NPCs is relatively small, using while loops for each NPC might be more suitable.

What’s your current use case? How many NPCs do you have?

3 Likes

my game is intended to have random events that spawn at specific objects i put around the map
This is a snippet from in game whereas I spawn 4 Clones with the same AI which means its a while loop 0.5 x 4

				for i = 1, 4 do
					MobHandler.CreateEntity('Zetsu', {
						replicate = true, 
						cframe = root * CFrame.new(math.random(-3,4),3,math.random(-3,4));
						summoneffect = true;
					})
				end

I fear this may overload the server as I am in a testing place running mini events with around 8 NPCS and running 40-50fps on my client through the Roblox website.

My judgement is based off other games that use AI like I do yet more efficiently as I’ve seen a user exploit clones and spawn over 100 with me running < 20 FPS stably on a 3k resolution monitor.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.