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

Where to add debounce function?

The Sound plays multiple times when a humanoid touch the brick but i don't know where to add the debounce function (once again! lol)

function onTouched(hit)
          H = hit.Parent:FindFirstChild("Humanoid")
               if H ~= nil then
	script.Parent.Coin:play()
    end
end
script.Parent.Touched:connect(onTouched)

2 answers

✓ Accepted answer

Debounce doesn't have to be in a function, and I normally don't use a debounce function because I use different kinds of debounce all the time. For this, I would assume you only want the coin sound to play at most once every second.

local deb = false --Your debounce variable. As with any variable, the name doesn't really matter.

function onTouched(hit)

	if deb then return end --if deb is set to true, this will exit the function without running any code.
	deb = true --sets your debounce. The function is now "disabled"

	local H = hit.Parent:FindFirstChild("Humanoid")
	if H then --~= nil is never necessary, due to the concept of Truthyness
		script.Parent.Coin:play()

		wait(.5) --This wait goes inside your if check because if the thing that caused the Hit event doesn't cause the coin sound to play, why disable it from playing?

	end

	deb = false --"enables" the function. If the coin sound actually played, this will happen half a second after the sound played. If it didn't, this will happen instantly.

end
script.Parent.Touched:connect(onTouched)

1 comment

0

Thanks you! :D

Heres an example

function onTouched(hit)
deb = false
H = hit.Parent:FindFirstChild("Humanoid")
if H ~= nil then
if deb = false then
deb = true
script.Parent.Coin:play()
else
deb = false
script.Parent.Coin:stop()
end
end
end
script.Parent.Touched:connect(onTouched)

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