Need help with adding a cooldown to my sword

So ive created this sword, that keeps switching between animations.
how would it be possible to create a cooldown inbetween its animation?
So 1 swings, wait 1, 2 swings wait 1. repeat.

Ive tried adding wait(1) at different parts but it didnt work. So does someone know what im doing wrong?

local t = 1

script.Parent.Activated:Connect(function()

	
	local animation1 = script.Animation1
	local animation2 = script.Animation2
	local humanoid = script.Parent.Parent.Humanoid
	
	local animationtrack1 = humanoid:LoadAnimation(animation1)
	local animationtrack2 = humanoid:LoadAnimation(animation2)
	local Sound = script.Sword
	
	
		if t == 1 then
		    animationtrack1:Play()
            Sound:Play()
			t = 2
		elseif t == 2 then
			animationtrack2:Play()
            Sound:Play()
		    t = 1
		
		
		
	end
	end)

1 Like

This script here should work.

local t = 1
local debounce = false

script.Parent.Activated:Connect(function()
	if debounce then return end -- If the debounce is activated, stop the execution of the function
	debounce = true -- Active debounce
	
	local animation1 = script.Animation1
	local animation2 = script.Animation2
	local humanoid = script.Parent.Parent.Humanoid

	local animationtrack1 = humanoid:LoadAnimation(animation1)
	local animationtrack2 = humanoid:LoadAnimation(animation2)
	local Sound = script.Sword
	
	if t == 1 then
		animationtrack1:Play()
		Sound:Play()
		t = 2
	elseif t == 2 then
		animationtrack2:Play()
		Sound:Play()
		t = 1
	end
	
	task.wait(1) -- Cooldown time
	debounce = false -- Deactivate debounce
end)

For more information: Debounce Patterns | Roblox Creator Documentation

3 Likes