How to add a cooldown to this loot script?

I have this script for looting. Whenever the player clicks it, it does a math.random and gives them a random item. The problem is that I want to add a cooldown, but I don’t know how. Help?

local Detector = script.Parent.ClickDetector
local ItemsStorage = game.ReplicatedStorage.Items

 
Detector.MouseClick:Connect(function(Player)
	local character = Player.Character
	local humanoid = character.Humanoid	
	local PickUp = humanoid:LoadAnimation(script.PickUpAnim)
	
	local randomnumber = math.random(1, 5)
	
	if randomnumber == 5 then 
	PickUp:Play()
	local Clone = ItemsStorage.Clothing.DBlueJeans:Clone()
    Clone.Parent = Player.Character
	end
	
	if randomnumber == 4 then 
	PickUp:Play()
	local Clone = ItemsStorage.Clothing.DBrownJeans:Clone()
	Clone.Parent = Player.Character
	end
	
	if randomnumber == 3 then 
	PickUp:Play()
	local Clone = ItemsStorage.Clothing.DWhiteTShirt:Clone()
	Clone.Parent = Player.Character
	end
	
	if randomnumber == 2 then 
	PickUp:Play()
	local Clone = ItemsStorage.Clothing.RedFlannelShirt:Clone()
	Clone.Parent = Player.Character
	end
	
	if randomnumber == 1 then 
	PickUp:Play()
	local Clone = ItemsStorage.Clothing.FishingHat:Clone()
	Clone.Parent = Player.Character
	end

	
	
end)

is this a local or server script?

its a server script inside of a union

Do you want a cooldown per player, or for everyone?

Outside the MouseClick function, add a variable named debounce. Then after the MouseClick line, check if debounce is true. If it’s true, then return. If it’s not then on the next line, set debounce to true. At the end of the function, add a wait, then set debounce to false.

local debounce = false
Detector.MouseClick:Connect(function(Player)
	if debounce then return end
	debounce = true
	...
	task.wait(5) -- Change this
	debounce = false
end)

for everyone, so that one spot can’t be looted more than once

Ok, in that case, the solution provided by @Lielmaster should work, although I would recommend using task.wait(time here) as wait() is deprecated.

1 Like