I'm a beginner to Roblox scripting and I was trying to make a combat script and I wanted to add a delay after you press a key to attack to prevent just outright button spamming combat but it seems like wait(n) is not working? I've tried various different values and it just does not work for some reason. Any help would be appreciated, thanks in advance.
-- Delays local punchDelay = 1.5 -- !! MOVE TO SERVERSIDE !! local kiBlastDelay = 2.5 -- !! MOVE TO SERVERSIDE !! --- Actions local function punch() print("punch()") -- !! MAKE THIS SERVERSIDE !! (Remote functions) -- TO-DO: animation -- TO-DO: damage n stuff -- TO-DO: increase stats game.ReplicatedStorage.playSound:FireServer(0) game.ReplicatedStorage.IncreaseXp:FireServer() end local function kiBlast() print("kiBlast()") -- !! MAKE THIS SERVERSIDE !! (Remote functions) -- TO-DO: animation -- TO-DO: damage n stuff -- TO-DO: increase stats game.ReplicatedStorage.playSound:FireServer(1) game.ReplicatedStorage.IncreaseXp:FireServer() end userInputService.InputBegan:Connect(function(input, GPE) local lastInputEnum = userInputService:GetLastInputType() if lastInputEnum == Enum.UserInputType.Keyboard or string.find(tostring(lastInputEnum.Name), "MouseButton") or lastInputEnum == Enum.UserInputType.MouseWheel then -- Keyboard if input.KeyCode == keyboard_punch then punch() wait(punchDelay) elseif input.KeyCode == keyboard_kiBlast then kiBlast() wait(kiBlastDelay) end elseif string.find(tostring(lastInputEnum.Name), "Gamepad") then -- Gamepad (Controller) if input.KeyCode == gamepad_punch then punch() wait(punchDelay) elseif input.KeyCode == gamepad_kiBlast then kiBlast() wait(kiBlastDelay) end end wait(.1) end)
This is due to how events in roblox work. Any event can and often will be fired multiple times simultaneously, even if the function for the event hasn't finished up (hence why the attack can be done faster than you'd think wait(.1)
would allow)
The easiest fix is to use a variable to act as a "cooldown." This is often called debouncing.
This is a veeerrry basic example of how you'd implement something like this. Every time you press E, "attacked!" is printed to the output. There's a cooldown of 1 second.
local UserInputService = game:GetService('UserInputService') local AttackCooldown = false local function Attack() print('attacked!') end UserInputService.InputBegan:Connect(function(input) if input.KeyCode == Enum.KeyCode.E then if AttackCooldown == true then -- If the attack is on cooldown, stop here. return end -- Now just set the cooldown to true, attack, -- wait, and set it back to false. AttackCooldown = true Attack() wait(1) AttackCooldown = false end end)
This should be fairly easy to implement in your current code. Let me know if you have any questions!