I recently made a script that spawns Zombies when the folder has x amount of zombies left, it repeats and Im seeing server lag, is there any way I can fix this with it still looping?
Code:
while true do
wait(5)
local Spawns = workspace:WaitForChild("World").Objects:WaitForChild("Map").Locations:GetChildren()
local NPC = replicatedStorage:WaitForChild("Assets").Zombies:GetChildren()
local rand = math.random(1,#NPC)
if game.ReplicatedStorage.Match.Value == true then
local children = workspace:WaitForChild("World").Objects:WaitForChild("Map").Zombies:GetChildren()
local loco = game.Workspace:WaitForChild("World").Objects:WaitForChild("Map").Zombies
local count = #children
if count < 6 then
task.wait(math.random(3,6))
local NPCs = NPC[rand]:Clone()
NPCs:PivotTo(Spawns[math.random(#Spawns)].CFrame)
NPCs.Parent = loco
else
task.wait(1)
end
else
print("Cannot spawn, match isn't ready")
end
From what I can see, I don’t really understand why the server is lagging (assuming the lag you are referring to is not from a Script Timeout error). Perhaps the lag is occurring over time from memory build-up and/or memory leakage.
However, you don’t necessarily have to be constantly checking for a decrease in the count of zombies. Instead, you can connect an event to fire when a child (zombie) is removed from the folder.
loco.ChildRemoved:Connect(function(child)
-- Continue from here
end)
This event will use less memory than constantly checking with a while loop, and hence, reduced server lag over time, but it will also allow you to disregard the check for when the value of Match is true as you can simply connect the event when needed. Remember to disconnect the event when you no longer need it, to prevent memory leakage (arguably one of the main ways server lag builds-up).