Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Debounce/Wait time on Sound playing when pressing Gui?

Asked by 4 years ago

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

Log in to vote
0
Answered by 4 years ago
Edited 4 years ago

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.

Ad
Log in to vote
0
Answered by 4 years ago

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

Answer this question