Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How and where can I add a cooldown to this script?

The script below activates an hit animation when the player clicks their screen:

local Tool = script.Parent
local Animation = Tool.Animation

Tool.Activated:Connect(function()
	local Character = Tool.Parent
	local Humanoid = Character.Humanoid

	local AnimationTrack = Humanoid:LoadAnimation(Animation)
	AnimationTrack:Play()
end)

There is no cooldown however, so the player can do it infinitely.

Can someone tell me how I can add a cooldown so that the player can't click and attack until a specific time period ends?

I'd also like to know where in the script I'm supposed to put it, at the beginning or the end, because that kind of stuff confuses me :)

3 answers

✓ Accepted answer

Hey King,

You can either create the cooldown on the server via a RemoteEvent or have a cooldown inside your LocalScript. For this example, I'll put the cooldown inside your LocalScript.

The method I'm using is probably the most basic way you can do it.

local Tool = script.Parent
local Animation = Tool.Animation
local activeCooldown = false
local cooldownTime = 10 -- 10 second cooldown

Tool.Activated:Connect(function()
	if (activeCooldown) then
		return -- if they have an active cooldown, then nothing will happen
	else
		activeCooldown = true 
		
		local Character = Tool.Parent
		local Humanoid = Character.Humanoid

		local AnimationTrack = Humanoid:LoadAnimation(Animation)
		cooldownTime = AnimationTrack.Length

		AnimationTrack:Play()
		
		wait(cooldownTime) -- wait x amount of seconds to make the cooldown false
		
		activeCooldown = false -- makes the cooldown false again
	end
end)

1 comment

0

THANK YOU! This worked perfectly!! I will make sure to keep this in mind when trying to create other weapons w/ cooldowns!

local Tool = script.Parent
local Animation = Tool.Animation
local Debounce = false
local Time = 3 --Change The Cooldown Time

Tool.Activated:Connect(function()
	if Debounce == false then --If Debounce false
		
		--Set Debounce to True
		Debounce = true
		
		--Do Animation
		local Character = Tool.Parent
		local Humanoid = Character.Humanoid

		local AnimationTrack = Humanoid:LoadAnimation(Animation)
		AnimationTrack:Play()
		
		--Set Debounce to False
		wait(Time)
		Debounce = false
	else --If Debounce true
		return --Return(Do Nothing)
	end
end)

Just add a wait a "Wait()" Function, like this:

local Tool = script.Parent
local Animation = Tool.Animation
 
Tool.Activated:Connect(function()
    local Character = Tool.Parent
    local Humanoid = Character.Humanoid
 
    local AnimationTrack = Humanoid:LoadAnimation(Animation)
    AnimationTrack:Play()
   wait(-enter cooldown number in seconds-)
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.