How to add in cooldown to a script

Hey there! Im trying to make a dash script where every 2 seconds, you can dash, though I’m having a little bit of trouble on my end.

local handle = require(game.ReplicatedStorage.Dash)
local uis = game:GetService("UserInputService")
local dbTime = handle.dashCooldown
local db = true

local function onInputBegan(input)
	if db and input.KeyCode == Enum.KeyCode.E then
		db = false
		handle.dash(game.Players.LocalPlayer)
	else
		task.wait(dbTime)
		db = true
	end
end
	
uis.InputBegan:Connect(onInputBegan)```
basically, its running the db = true function every time when I put in userinput, though I dotn want to do that. Its probably pretty easy to fix but I'm a little stumped. Any help would be greatly appreciated!!

I think I found what’s wrong. When db is false it just sets it to true.

if db and input.KeyCode == Enum.KeyCode.E then
	db = false
	handle.dash(game.Players.LocalPlayer)
else
	task.wait(dbTime) 
	db = true --here
end

You could put the stuff under else into the if statement.

if db and input.KeyCode == Enum.KeyCode.E then
	db = false
	handle.dash(game.Players.LocalPlayer)
	task.wait(dbTime) 
	db = true
end

I think I gotchu:

local handle = require(game.ReplicatedStorage.Dash)
local uis = game:GetService("UserInputService")
local dbTime = handle.dashCooldown
local db = true

local function onInputBegan(input, gameProcessedEvent)
	if gameProcessedEvent then return end
	if db and input.InputType == Enum.UserInputType.Keyboard and input.KeyCode == Enum.KeyCode.E then
		db = false
		handle.dash(game.Players.LocalPlayer)	
		task.delay(dbTime, function()
			db = true
		end)
	end
end
	
uis.InputBegan:Connect(onInputBegan)

Should fix the problems with trying to boost with each user input as well as fix an issue in the way db was only starting its cooldown after a dash was attempted while db was set to false

Try this code:

local handle = require(game.ReplicatedStorage.Dash)
local uis = game:GetService("UserInputService")
local dbTime = handle.dashCooldown
local db = true

local function onInputBegan(input)
	if db and input.KeyCode == Enum.KeyCode.E then
		db = false
		handle.dash(game.Players.LocalPlayer)
	    task.wait(dbTime)
		db = true
	end
end
	
uis.InputBegan:Connect(onInputBegan)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.