Heartbeat wont disconnect

landed prints multiple times but the heartbeat wont disconnect

local heartbeat1

function onJumpRequest()
	local char = Player.Character
	local rootPart = Player.Character:WaitForChild("HumanoidRootPart")
	
	heartbeat1 = RunService.Heartbeat:Connect(function()
	rootPart.CFrame = CFrame.new(rootPart.CFrame.p, rootPart.CFrame.p + Vector3.new(workspace.CurrentCamera.CFrame.LookVector.X,0,workspace.CurrentCamera.CFrame.LookVector.Z))
			
		if Player.Character.Humanoid:GetState() == Enum.HumanoidStateType.Landed then
            print("landed")
			heartbeat1:Disconnect()
		end	
	end)
end

UserInputService.JumpRequest:Connect(onJumpRequest)

1 Like

Is the function onJumpRequest being called multiple times? This could definitely cause it to happen. What you can also do is after disconnecting it, set it equal to nil. Then before doing the code in the jump state check, you can check if it’s equal to nil. Basically, you can make it so only 1 heartbeat can exist at once.

if heartbeat1 == nil then
    heartbeat1 = RunService.Heartbeat:Connect(function()
        rootPart.CFrame = CFrame.new(rootPart.CFrame.p, rootPart.CFrame.p + Vector3.new(workspace.CurrentCamera.CFrame.LookVector.X,0,workspace.CurrentCamera.CFrame.LookVector.Z))
        
        if Player.Character.Humanoid:GetState() == Enum.HumanoidStateType.Landed then
            if heartbeat1 == nil then return end
            print("landed")
            heartbeat1:Disconnect()
            heartbeat1 = nil
        end	
    end)
end
1 Like

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