I am pretty new to coding and i need help on where to place the cooldown part of a gun shoot script. From what i’ve seen cooldowns usually look like this
local cooldown = false
if cooldown == false then
cooldown = true
wait(2)
cooldown = false
end
But i really have no clue where i should place the cooldown part in the script, I’ve experimented a bit and it either doesn’t shoot or you can still spam. And during my testing there hasn’t been any errors in the output
Shoot Script
local gun = script.Parent
local re = script.Parent:WaitForChild("RemoteEvent")
local player = nil
local mouse = nil
local connection = nil
local function onActivated()
re:FireServer(mouse.Target)
end
gun.Equipped:Connect(function()
player = game.Players.LocalPlayer
mouse = player:GetMouse()
connection = gun.Activated:Connect(onActivated)
end)
gun.Equipped:Connect(function()
player = nil
mouse = nil
if connection then
connection:Disconnect()
end
end)
Any help will be appreciated as I am pretty lost right now
Hello, I have seen your code and noticed several things you should edit in your script. First of all, you have two functions or events named “Equipped.” This means that if you equip your tool or gun, both functions will be activated simultaneously.
Also, if you want the gun to shoot only when it is equipped, you need to use variables to manage its state, in other words, debounces.
local gun = script.Parent
local re = script.Parent:WaitForChild("RemoteEvent")
local plr = game.Players.LocalPlayer
local mouse = player:GetMouse() --You don´t need to call player and mouse a lot of times.
local toolEquipped = false -- This is a debounce
local Cooldown = true -- This is a debounce too
local cooldownTime = 2 -- You can adjust this as you need
local function onActivated()
if toolEquipped == true then
if mouse.Target and Cooldown then
re:FireServer(mouse.Target)
Cooldown = false --Cooldown
wait(cooldownTime) --Cooldown
Cooldown = true --Cooldown
end
end
end
gun.Equipped:Connect(function()
if not toolEquiped then
tooldEquipped = true
end
end)
gun.Unequipped:Connect(function()
if toolEquiped then
toolEquipped = false
end
end)
gun.Activated:Connect(onActivated)
This should work. Maybe my code is not the best because Lua is a really flexible programming language, meaning there are many ways to script.