How to disconnect all current loops of a runService loop

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”?

i would put all the event connections into a table and then when you want them disconnected, just loop through the table and run :Disconnect()

Wdym table?

so like this?

I’m not sure on how to access the loops for the movement part then (as you cans see in my example). How could I do this then?

where is your example? I don’t see it

He means something like this:

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
3 Likes

Or instead of creating a variable he can just do

local runService = game:GetService("RunService")
local Connections = {}
table.insert(Connections ,runService.Heartbeat:Connect(function()
   -- code
end)
1 Like

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

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.