Too many coroutines

Hello! I am trying to make an NPC framework but I have to make a coroutine for each and every NPC (i am recursively calling a walk random function). If I wanted 1000 NPCs, then I would need 1000 coroutines. How can I fix this?

Not much you can do here, other than some optimizations:

  • Disable the AI if the player is too far away
  • Also, do you really need 1,000 NPC’s? That seems a bit out of reach.
1 Like

1st point: I think I will implement this. Thanks for the advice.
2nd point: Also, you are right about the 1,000 NPCs. I will only be using around 10-100, but just for fun, I would like to try pushing the system to its limits.

I have something similar, but not with NPCs
basically I have a central script that loops through everything instead of a ton of coroutines. The benefit is that I can check X if they’re nearby or not, to have them active, or inactive to save performance.

Ex:

local function RefreshNPC(NPC)
 -- stuff for npc
end

local Players = game:GetService("Players")

while condition do
    for _, NPC in pairs(workspace.NPCs:GetChildren()) do
         local Active = false
         for _, player in pairs(Players:GetPlayers()) do
           if player:DistanceFromCharacter(NPC.Position) < 100 then
              Active = true
              break
           end
        end
        if Active == true then
             RefreshNPC(NPC)
        end
    end
end


I doubt you need all those coroutines for each NPC. I’m sure with some optimization you could control them with little to no coroutines. Why exactly do you need this?