Most efficient way to make a zombie controller script

This is my current code, it is pretty laggy. already without pathfinding when there is 30 zombies when the zombies are close together. Do you have any suggestions for optimization in my zombie controller script, we are aiming for 50 to 75 zombies. Also do you think is there any things I should optimize on currently.

   local AttackedPlayers = {}

local FreeZombies = workspace.Zombies:GetChildren()

local Targets = {}

local TagService = game:GetService(“CollectionService”)

for i,v in pairs(workspace.Zombies:GetChildren()) do
TagService:AddTag(v, “ZombiesNotAttacking”)
end

function GetNearestPlayer(Part)
local MagnitudeTable = {}

for i,v in pairs(game.Players:GetPlayers()) do
	
	if v.Character ~= nil then
		MagnitudeTable[v] = (v.Character.HumanoidRootPart.Position - Part.Position).Magnitude
		print(MagnitudeTable[v])
	end
end

local Lowest = math.huge
local LowestPlayer

for i,v in pairs(MagnitudeTable) do
	print(v)
	if v < Lowest then
		print "LESS THAN"
		Lowest = v
		LowestPlayer = i
	end
end

print(LowestPlayer)

return LowestPlayer

end

while true do
for i,v in pairs(workspace.Zombies:GetChildren()) do
if Targets[v] == nil then
local Humanoid = v:WaitForChild(“Humanoid”)
local Target = GetNearestPlayer(v.HumanoidRootPart)

		if Target ~= nil then
			Targets[v] = Target
		end
	else
		if Targets[v].Character.Humanoid.Health == 0 then
			Targets[v] = nil
		else
			v.Humanoid:MoveTo(Targets[v].Character.HumanoidRootPart.Position)
		end
		
	end
	
end
wait()

end

Uh why does code uploading always mess up

Since while loops are just no good in my opinions and there is always a way to avoid them I would use UserInputService instead such as mentioned in this thread.

Your code overall looks good although I don’t understand why you didn’t check all the players distance in the GetNearestPlayer function and just made a new function instead.

I think I might be wrong since the code is not formatted very well. Sorry.

Oh I did that getNearestPlayer thing, it wasnt a new function , sorry for the bad formatting. I will check the UIS article right now.

Alright so I checked it and it seems UIs is not good at this case, because in my games zombies can spawn near you sometimes. If I used UIS, then if a zombie spawned near a player and the player didnt press a key it wouldnt go to the player.

1 Like

So I guess while loops are your best choice here even if I know there is always another way.

You can always use RunService instead of while loops, even if that doesn’t make a big difference.

Sorry for late response, I was sleeping