[Punch System] How to implement a cooldown/debounce system?

Hello,

Earlier today, I made a punch system which is accessed by the player when they click. It works magnificently but I want to implement a cooldown/debounce system. This is because the player is able to punch repeatedly without a cool down per punch.

I am wondering how I would go about implementing the cooldown system inside of the script. I will attach the code below.

  local Player = game.Players.LocalPlayer
  local character = Player.Character
  local Humanoid = character:FindFirstChild("Humanoid")

  local UserInputService = game:GetService("UserInputService")

 local ReplicatedStorage = game:GetService("ReplicatedStorage")
 local Remotes = ReplicatedStorage:FindFirstChild("Remotes")
 local PunchEvent = Remotes:FindFirstChild("PunchEvent")

 local animation = Instance.new("Animation")
 animation.AnimationId = "rbxassetid://--AnimationID--"

 local CanDoDmg = true 
 local Keybind = Enum.UserInputType.MouseButton2
 local dmg = 10 

UserInputService.InputBegan:Connect(function(inputObject)
  if inputObject.UserInputType == Keybind then
	local Punch = Humanoid:LoadAnimation(animation)
	Punch:Play()
	PunchEvent:FireServer()
	
	Humanoid.Touched:Connect(function(hit)
		if hit.Parent == Humanoid and CanDoDmg == true then
			hit.Parent.Humanoid:TakeDamage(dmg)
			CanDoDmg = false
			wait(1)
			CanDoDmg = true
		 end
	 end)
   end
end)

Any help is appreciated. For your information, I will be modifying the script and not using Humanoid:LoadAnimation. Since, it is going to be Deprecated.

Sorry to be the bearer of bad news, but Humanoid:LoadAnimation is already deprecated.

Debounce is quite simple thing to apply to your script. Please read the help article and see it solves your problem. In essence, what you need to do is create a bool variable for debounce and put it in your .InputBegan thing.

For example:

local debounce = false
local cooldownDuration = 5

UserInputService.InputBegan:Connect(function(inputObject)
  if inputObject.UserInputType == Keybind then
        if debounce == false then 
            debounce = true 
            wait (cooldownDuration) 
            debounce = false
        else 
            return  -- This causes the function to stop here
        end

        local Punch = Humanoid:LoadAnimation(animation)
	Punch:Play()
     
	PunchEvent:FireServer()
1 Like

Already?!?!? That is a bummer. Welp, I guess I will have to change it then. Thanks for helping me with the cooldown/debounce system. I really appreciated it :slight_smile: Have a great day!

I’ve just updated the code, basically I put the debounce before Punch:Play() so the rest of the script doesn’t run when the debounce is false.

1 Like

Alright :slight_smile: Thanks very much!

1 Like