I want to disconnect the heartbeat event from the previous object when I create a new object. When I create a new object, I set the old object to nil
The heartbeat event is inside of a separate module script and is called inside of a method
local Player = self.Player
local Char = Player.Character or Player.CharacterAdded:Wait()
local HMR = Char:WaitForChild("HumanoidRootPart")
runService.Heartbeat:Connect(function() -- Keeps printing out hi even after I have set the object to nil
print("hi?") -- How do I disconnect this?
if self.passiveEffect then -- This is inside the method
self.passiveEffect(self) -- This runs stinkPassive()
This article might help you, since you may have to use Disconnect() for that issue, which disconnects that function.
Example of Disconnect() being used:
local points = Instance.new("NumberValue")
points.Name = "Points"
points.Value = 0
local function onPointsChanged(newPoints)
print("Points: " .. newPoints)
if newPoints >= 50 then
-- Stop listening for changes if we have at least 50 points
connection = points.Changed:Connect(onPointsChanged)
-- Trigger some changes
points.Value = 25
points.Value = 100
points.Value = 0 -- Prints nothing because we called Disconnect()
Whenever I equip a new tool to the backpack, I create a weapon object for it, that weapon class has a method that gives a damage effect to it. Inside that same method I call a function from a different module script and inside the called function contains a runService heartbeat event and it won’t stop. I want to find a way to stop that runService heartbeat event when I set the object to nil.
You can then simply disconnect it when you destroy the object directly, or indirectly using a maid:
Alternatively, you can cancel the connection using an error handler in the Heartbeat function:
connection = RunService.Heartbeat:Connect(function()
local success = pcall(function()
-- make a notion to the object, or have a value in the self table signifying if the table is active
if not success then
You can disconnect from anywhere you have a reference to the object itself. If you are just scanning the workplace and :Destroy() on the instance of it then you aren’t making use of the OOP object class.
Seeing as how you are referencing self.passiveEffect above, I am hoping you are keeping track of objects you create with your OOP class somewhere to utilize them everywhere. If you are, it won’t matter where you Disconnect since you will be doing so on the object itself.
Yes that is correct. Maids are just as the name implies, something that handles things for you. Indirectly cleaning up connections. Otherwise, directly managing the state is what you just accomplished by typing out the Disconnect event in the specific spot the state required it to be done.
The article linked in that post sums it all up nicely.