.Touched being disabled and still firing?

The script is supposed to make the tool (a chainsaw) turn on and do damage when the player holds down the mouse. When the mouse is not held down anymore, it should not do damage. My problem is that when you hold the mouse down and stop holding it down, it still does damage. I checked the forum for similar problems, but I couldn’t find any.

local attack_mode = false

script.Parent.Equipped:Connect(function(Mouse)
	script.Parent.Chainsaw_Idle:Play()
	Mouse.Button1Down:Connect(function()
		attack_mode = true
		animation = game.Players.LocalPlayer.Character.Humanoid:LoadAnimation(script.Parent.Animation)
		animation.Priority = Enum.AnimationPriority.Action
		animation.Looped = true
		animation:Play()
		script.Parent.Chainsaw_Attack:Play()
		script.Parent.Blade.Kill_Part.Touched:Connect(function(hit)
			local hitHumanoid = hit.Parent:FindFirstChild("Humanoid")
			if hit ~= nil then
				if attack_mode == true then
					hitHumanoid:TakeDamage(10)
				end
			end
		end)
	end)
end)

script.Parent.Unequipped:Connect(function()
	animation:Stop()
	script.Parent.Chainsaw_Idle:Stop()
	script.Parent.Chainsaw_Attack:Stop()
	local attack_mode = false
end)

script.Parent.Equipped:Connect(function(Mouse)
	Mouse.Button1Up:Connect(function()
		animation:Stop()
		script.Parent.Chainsaw_Idle:Play()
		script.Parent.Chainsaw_Attack:Stop()
		local attack_mode = false
	end)
end)
Tool.Equipped:Connect(function()
	print("A tool was equipped")
end)
2 Likes

The problem with what you’re doing is that the function is initializing/stacking, and then they still continue, even after the tool is unequipped, This is a better way to do this.

local MouseDown = false
local ToolEquipped = false

Mouse.Button1Down:Connect(function()
   MouseDown = true
   if MouseDown == true and ToolEquipped == true then
        animation = game.Players.LocalPlayer.Character.Humanoid:LoadAnimation(script.Parent.Animation)
		animation.Priority = Enum.AnimationPriority.Action
		animation.Looped = true
		animation:Play()
		script.Parent.Chainsaw_Attack:Play()
   end
end)

Mouse.Button1Up:Connect(function()
	MouseDown = false
    animation:Stop()
	script.Parent.Chainsaw_Idle:Play()
	script.Parent.Chainsaw_Attack:Stop()
end)
Tool.Equipped:Connect(function()
   ToolEquipped = true
end)
Tool.Unequipped:Connect(function()
	ToolEquipped = false
    animation:Stop()
	script.Parent.Chainsaw_Idle:Play()
	script.Parent.Chainsaw_Attack:Stop()
end)

script.Parent.Blade.Kill_Part.Touched:Connect(function(hit)
    local hitHumanoid = hit.Parent:FindFirstChild("Humanoid")
	if hit ~= nil then
		if MouseDown == true and ToolEquipped == true then
			hitHumanoid:TakeDamage(10)
		end
	end
end)

Thank you so much! I really appreciate your help. :smiley:

1 Like

Of course. Stay motivated, and keep coding. :slight_smile: