So I’am making a TD game and what I have been doing is to render the enemies on the client and have a parallel loop that moves the enemies on the server (pure data).
My problem is that when the enemies destroy the base I want to get rid of all enemies. Removing all models from the client was easy but I have no idea how to disconnect all ongoing runService loops for each enemy (data on the server) there is.
So is there a way to just disconnect all currently running loops from a loop at once?
You can imagine it as this:
for i = 1, enemyAmount, 1 do
local loop
loop = runService.Heartbeat:Connect(function()
"do stuff"
end
end
How could I break every loop under the variable “loop”?
local runService = game:GetService("RunService")
local loops = {}
for i = 1, enemyAmount, 1 do
local loop = runService.Heartbeat:Connect(function()
-- do stuff
end
table.insert(loops, loop)
end
-- Put the code below whenever you want to disconnect the loops.
for i,v in loops do
v:Disconnect() -- Disconnect after.
end
I think it would be more efficient to have one Heartbeat loop instead of having one for every NPC. As to how the loop will access the NPCs, you could add each NPC you make to a table, which the Heartbeat loop will get the NPCs from and do whatever it needs from there. This way, you don’t even need to disconnect the Heartbeat.
You would need to disconnect it later anyways. That’s because when the enemy enters the base and gets destroyed the loop would still run, you don’t want that