How can I run multiple npcs without using for-loop?

Hi. I’ve been making a simple NPC framework for my game and I noticed how inefficient it is for my game. Here is what is looks like:

for i = 1, #self.zombs do
	local hum = self.zombs[i].render_obj.Humanoid
		
	hum.Jump = jump
		
	if no_path then
		-- just move to the player
		hum:MoveTo(self.target.Position)
	else
		-- move to the waypoitns
		hum:MoveTo(current.Position)
	end
		
	-- add a function in the zombie that will detect if the zombie can't move
end

The problem with it is that it loops through each one, one by one, and moves the NPC. This can get really bad especially if you want to put a lot of NPCs (like I want to do) and possibly wreck the script. Thus, I want to remove it from my framework, but I don’t really know how. How can I achieve this? Please leave suggestions below.

EDIT: sorry if I reply late I have to get off the pc.

I think you could just spawn a thread that handles each of the NPC on their own.

yeah I have done that before but I heard that it would kill the server.

It’ll only kill the server if you spawn too much threads like a 20-30.

You could try using coroutines. Coroutines are specifically designed to perform multiple tasks at the same time. So if you were trying to make multiple NPC movement functions perform simultaneously, this would work.

You could have multiple threads but each thread would handle lets say 5 zombies at a time

I’m planning to make around 50-75 npcs per thing, so…

yeah. that is what I was thinking, too. I was going to divide up the work and have each coroutine run around 5 Npcs. I will mark as solution because it is what I will try.

You could also try optimizing the zombie script too.
One way you could do this is by having two update loops for the zombie.
One for pathfinding that runs 4 times a second and another one for hit detection that runs every frame

I’m not sure but I think spawn() will help.

Ok. Thanks for the tips! They are really helpful.

1 Like