Function executes without tool being activated

I have a tool that im trying to add a click and hold function to so it makes the animation and mine function keep playing over and over again until you click again.

The issue i’m facing is that I’m able to play the animation and function without even having the tool equipped.

Gif of the issue: https://gyazo.com/6019f1d37b7052e27b432b454b7edba2

Code:

local Player = game.Players.LocalPlayer
local Character = Player.Character
local Humanoid = Character.Humanoid
local mouse = Player:GetMouse()

local PickaxeEquipAnim = script.Parent:WaitForChild("PickaxeEquip")
local MineAnim = script.Parent:WaitForChild("Mine")

local MineAnimation = Humanoid:LoadAnimation(MineAnim)
local PickaxeEquip = Humanoid:LoadAnimation(PickaxeEquipAnim)

PickaxeEquip.Looped = true



local canSwing = false
local mousedown = false

local debounce = 0.8


local function Mine()
	if canSwing == true then
		canSwing = false
		
		print("hit")
		MineAnimation:Play()
		MineAnimation:AdjustSpeed(0.5)
		
		wait(debounce)
		canSwing = true
	end
end

script.Parent.Activated:Connect(function()
	mouse.Button1Down:Connect(function()
		mousedown = true
		if canSwing == true then
			repeat
				Mine() 
			until mousedown == false or canSwing == false
		end

	end)

	mouse.Button1Up:Connect(function()
		mousedown = false
		MineAnimation:Stop()
		PickaxeEquip:Play()
	end)

end)


script.Parent.Equipped:Connect(function()
	PickaxeEquip:Play()
	canSwing = true
end)

script.Parent.Unequipped:Connect(function()
	PickaxeEquip:Stop()
	mousedown = false
	canSwing = false
end)

You are connecting mouse.Button1Down and Button1Up events every time you use the tool which is completely wrong in this case (it will basically connect 10 functions if you used the tool 10 times), i feel like your code will work without any Activated events

But you might have to add additional checks if the tool is equipped or not inside Button1Down and Button1Up connected functions

mouse.Button1Down:Connect(function()
	mousedown = true
	if canSwing == true then
		repeat
			Mine() 
		until mousedown == false or canSwing == false
	end
end)

mouse.Button1Up:Connect(function()
	mousedown = false
	MineAnimation:Stop()
	PickaxeEquip:Play()
end)


script.Parent.Equipped:Connect(function()
	PickaxeEquip:Play()
	canSwing = true
end)

script.Parent.Unequipped:Connect(function()
	PickaxeEquip:Stop()
	mousedown = false
	canSwing = false
end)
1 Like