Animation keeps playing even though there's a cooldown

The script does play the animation but the animation keeps playing when I click a lot. How do I fix this? I have already added debounce.

local canAttack = false

script.Parent.Equipped:Connect(function()
	local tool = script.Parent
	local character = tool.Parent
	local player = game.Players:GetPlayerFromCharacter(character)
	if not player.Character:FindFirstChild("swordanimation") then
		local animation = Instance.new("Animation", player.Character)
		animation.Name = "swordanimation"
		animation.AnimationId = "rbxassetid://5022307120"
	end
	script.Parent.Activated:Connect(function()
		local humanoid = player.Character.Humanoid
		local swordanimation = player.Character.swordanimation
	    local animationTrack = humanoid:LoadAnimation(swordanimation)
		if canAttack == false then
			canAttack = true
			animationTrack:Play()
			wait(tonumber(debounce))
			canAttack = false
		end
	end)
end)

There is no need to load the animation for the humanoid every time the tool is activated. Just load it in the beginning. Also, why are you checking to see if canAttack is false? Shouldn’t it be true?

Anyway, here’s a script I made:

local canAttack = true
local debounce = 5

local tool = script.Parent
local animation = Instance.new("Animation")
local animationTrack

animation.Name = "SwordAnimation"
animation.AnimationId = "rbxassetid://5022307120"

tool.Equipped:Connect(function()
    local character = tool.Parent
    if not animationTrack and character and character:FindFirstChild("Humanoid") then
        animationTrack = character.Humanoid:LoadAnimation(animation)
    end
end)

tool.Activated:Connect(function()
    local character = tool.Parent
    if animationTrack and canAttack and character and character:FindFirstChild("Humanoid") then
        canAttack = false
        animationTrack:Play()
        wait(debounce)
        canAttack = true
    end
end)
2 Likes