So I've made a framework for my game that I've been updating recently in order to accommodate more mechanics such rest animations, shooting animations, etc. What I'm trying to figure out is how to make it so when a player fires a shot they have to wait a certain amount of time in order to fire again. I'm relatively new to scripting.
Code used:
--//Shooting Animation Segment script.Parent.Activated:Connect(function(onMouseClick) local shooting = game.Players.LocalPlayer.Character.Humanoid:LoadAnimation(script.Parent.Shoot) local sound = game.StarterPack.Pistol.Sound sound:Play() shooting:Play() wait(1) end)
(Sound does not play for other players, only for the player using the tool, but that's a bit unrelated.)
If somebody could tell me my error or give me tips on how to fix it I'd greatly appreciate it.
Hi littlekit,
local debounce = true; function fire() if debounce then debounce = false -- Shut the door so function doesn't run until debounce is true. -- All of your code goes in here. wait(2) debounce = true -- Open the door for function to run. end end
Thanks,
Best regards,
Idealist Developer
You have to use a debounce
, commonly known as a cooldown. Try this:
local debounce = false local cooldownTime = 1 script.Parent.Activated:Connect(function() if not debounce then debounce = true local shooting = game:GetService("Players").LocalPlayer.Character.Humanoid:LoadAnimation(script.Parent.Shoot) local sound = game:GetService("StarterPack").Pistol.Sound sound:Play() shooting:Play() wait(cooldownTime) debounce = false end end)
The if statement checks if debounce is false. If it is, it makes debounce true and waits 1 second, then makes it false. Also, I added :GetService
as improvements.