How do I stop the runservice heartbeat?

Currently my issue is stopping it. The way it works is that once the player dies, the camera will follow the head until the player respawns. However, what it is doing is despite the player respawning, it is still tweeting to the location of the old position of the head.

I am unsure on how to stop this process and I tried to look at other devforum posts that had a slightly similar issue or even had a connection to RunService, returning with no luck.

This is the local script that it works in.

game.Players.LocalPlayer.Character:WaitForChild("Humanoid").Died:Connect(function()
local char = game.Players.LocalPlayer.Character --Funny formatting goes brrt
game:GetService("RunService").Heartbeat:Connect(function()
	local randomtween = ts:Create(Workspace.CurrentCamera, TweenInfo.new(3), {CFrame = CFrame.lookAt(Workspace.CurrentCamera.CFrame.Position, char:FindFirstChild("Head").Position)})
	randomtween:Play()
end)
end)
4 Likes

When you make a connection with :Connect it will return a RBXScriptConnection that you can do:

:Disconnect()

on to end the connection.

Example:

local conn = game:GetService("RunService").Heartbeat:Connect(function()
end)
-- this returns a RBXScriptConnection that you can then disconnect with
conn:Disconnect()

And if you want to disconnect the event from within:

local conn; -- unless you're using global variables, you'll need to define it outside of the connection I believe so you can actually access the local variable you just defined if that makes any sense
conn = game:GetService("RunService").Heartbeat:Connect(function()
    if someRandomCondition then
        conn:Disconnect() -- bam
    end
end)

So in your use-case:

game.Players.LocalPlayer.Character:WaitForChild("Humanoid").Died:Connect(function()
	local char = game.Players.LocalPlayer.Character --Funny formatting goes brrt
	local signal = game:GetService("RunService").Heartbeat:Connect(function()
		local randomtween = ts:Create(Workspace.CurrentCamera, TweenInfo.new(3), {CFrame = CFrame.lookAt(Workspace.CurrentCamera.CFrame.Position, char:FindFirstChild("Head").Position)})
		randomtween:Play()
	end)
	-- disconnect :sunglasses:
	signal:Disconnect()
end)
8 Likes

The fact that it was this simple makes me question everything I do.

5 Likes

Welcome to programming! Spending 4 hours trying to solve a problem that took 1 stupidly simple line of code to fix :sob: (100% not personal)

13 Likes