How to stop this function when tool is unequipped

Hi, my name is ShieldDevs, you can call me shield. I’m a scripter and a game developer.

Lately, I’ve been wanting to make a script that makes your arms follow your mouse, and I’ve done it, so now I needed to make it only work when a tool is equipped, and here’s my script:

script.Parent.Equipped:Connect(function()
	local Players = game:GetService("Players")
	local RunService = game:GetService("RunService")

	local plr = Players.LocalPlayer
	local char = script.Parent.Parent
	local mouse = plr:GetMouse()
	
	local Torso = char:WaitForChild("Torso")
	
	local armOffset = Torso.CFrame:Inverse() * char["Right Arm"].CFrame
	local armOffset2 = Torso.CFrame:Inverse() * char["Left Arm"].CFrame

	local armWeld = Instance.new("Weld")
	armWeld.Part0 = Torso
	armWeld.Part1 = char["Right Arm"]
	armWeld.Parent = char


	local armWeld2 = Instance.new("Weld")
	armWeld2.Name = "Num2"
	armWeld2.Part0 = Torso
	armWeld2.Part1 = char["Left Arm"]
	armWeld2.Parent = char


	RunService.Heartbeat:Connect(function()
		local cframe = CFrame.new(Torso.Position, mouse.Hit.Position) * CFrame.Angles(math.pi/2, 0, 0)
		armWeld.C0 = armOffset * Torso.CFrame:toObjectSpace(cframe)
		armWeld2.C0 = armOffset2 * Torso.CFrame:toObjectSpace(cframe)
	end)

and it works fine, but I want it when the tool is unequipped to stop the arm following, so is there any way I can do that?

Thanks,
ShieldDevs

1 Like

use the “Tool.Unequipped” event

I did already, but I don’t know how to make it stop the arms from following the mouse

you could just use a variable that stores the normal C0 motor6d and when an unequipped event happens, it disconnect the heartbeat function and set the motor6d to that variable

1 Like

Store the heartbeat as a variable of ‘Connection’ and then do Connection:Disconnect() whenever you want it to stop.

1 Like

Will try that right now, thank you!

if you’re talking about the RunService you can actually assign the connection to a variable
(code example)

local connection
script.Parent.Equipped:Connect(function()
    ...
    connection = RunService.Heartbeat:Connect(function()
		local cframe = CFrame.new(Torso.Position, mouse.Hit.Position) * CFrame.Angles(math.pi/2, 0, 0)
		armWeld.C0 = armOffset * Torso.CFrame:toObjectSpace(cframe)
		armWeld2.C0 = armOffset2 * Torso.CFrame:toObjectSpace(cframe)
	end)
end)
script.Parent.Unequiped:Connect(function()
    connection:Disconnect()
end)
3 Likes

I’ll try it right now, thank you, really appreciate your help

1 Like