Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to add a delay in between gunshots?

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.

2 answers

✓ Accepted answer

Hi littlekit,

In this case you need to use a debounce. Debounces can make your script have a 'cooldown period.' It just uses a boolean to test whether the function can run again. In basic terms, think of it like a gate that opens and closes. It looks like this:

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

##Go here to find out more about debounces.

Thanks,

Best regards,

Idealist Developer

2 comments

0

Thanks alot! This is going to help in the framework.

0

Glad to help :)

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.

1 comment

0

Don't forget to use debounce also on the server, so players can't exploit to shoot really fast

This discussion is preserved as it was. New answers, comments, and votes are closed.