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

Debounce/Wait time on Sound playing when pressing Gui?

So, I made this script & I also have a gui that plays the sound when it's clicked, but I want to make it so in my game people can't spam the sound, I want it to have a wait time before it's able to be clicked to make a sound again. Help?

function Click() script.Parent.Assis:Play() print("Request of Entry R1L1 was made")

end

script.Parent.ClickDetector.MouseClick:connect(Click)

-- I tried putting wait() times in there, and if & then statements, but nothing seems to work??

2 answers

Input detection usually fires events, and an event can be fired whenever. When you do Event:Connect(FUNCTION) you tell the internal event handler to run that function and pass the event's arguments to the function whenever the event is fired. This means that putting a wait inside of the connected function will only effect the environment inside of the function and not the time before that event can be fired again; the connected function does not yield the parent environment. So what you need to do is create some kind of "cooldown".

Example code:

local lastActivated = 0
local cooldown = 10 -- How long to wait between activations

function Clicked()
	if lastActivated + cooldown >= os.time() then return end -- If the time that it was last activated is less then 10 seconds before the current click then stop running the function
	
	script.Parent.Assis:Play() -- Play your sound
	
	lastActivated = os.time() -- Save the time that it was activated
end

ClickedEvent:Connect(Clicked) -- Connect the "Clicked" function to some form of click event

Hope this answer isn't too wordy.

you can use a debounce in the script like this:

function Click() script.Parent.Assis:Play() print("Request of Entry R1L1 was made")

end

local deb = false

script.Parent.ClickDetector.MouseClick:connect(function()
	if deb == false then
		deb = true
		Click()
		wait(WaitTimeHere)
		deb = true
	end
end

and make sure the "local deb = false" part is not in a loop or any other way that the line can be ran more than once

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