Hi, I have a script in a brick that's supposed to make a sound play when the brick is touched by the player. It looks like this:
local SP = script.Parent function onTouch(hit) local H = hit.Parent:FindFirstChild("Humanoid") if H ~= nil then SP.S:Play() end end script.Parent.Touched:connect(onTouch)
The problem is, I can't find a way to make it wait a little while after touched to perform the action again. The sound plays repeatedly so long as the player is touching the brick. I thought the obvious solution was to add a wait() after when the sound plays, but that didn't work, nor did making it wait until the player is finished touching it to execute again. It may be a simple answer, but how can I fix this?
Hi SuperJumpman12,
local SP = script.Parent local deb = false; local S = SP.S; -- The sound I assume. function onTouch(hit) if deb then return end deb = true; local H = hit.Parent:FindFirstChild("Humanoid") if H ~= nil then S:Play() end end script.Parent.Touched:connect(onTouch) --[[ Now, I'm going to set deb back to false when the sound's .Stopped event is run. You can use various other methods to get deb back to false, such as making a wait of the amount of time it takes to play the song, and then setting deb back to false but, I think using this method is the best since it's not complicated at all, seems better organized and efficient-enough. --]] S.Stopped:Connect(function() deb = false; -- Sets deb back to false so that the function can run once again. end);
local SP = script.Parent local deb = false; local S = SP.S; -- The sound I assume. function onTouch(hit) if deb then return end deb = true; local H = hit.Parent:FindFirstChild("Humanoid") if H ~= nil then S:Play() end wait(S.TimeLength); deb = false; end script.Parent.Touched:connect(onTouch)
Thanks,
Best regards,
~~ KingLoneCat
Debounce.
local debounce = false local SP = script.Parent function onTouch(hit) if debounce then return end debounce = true local H = hit.Parent:FindFirstChild("Humanoid") if H ~= nil then SP.S:Play() end wait(1) -- Change this to how long you want the cooldown to last for. debounce = false end script.Parent.Touched:Connect(onTouch) -- connect is deprecated; use Connect.
local SP=script.Parent local Buffer=false function onTouch(hit) local H=hit.Parent:FindFirstCHild("Humanoid") if H and Buffer==false then SP.S:Play() Buffer=true SP.S.Ended:connect(function() Buffer=false end) end end
Try this. Didn't test it, let me know if it works.