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()
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.
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.