I'm making a scary game, and I'm trying to make it so that once the player goes back inside the house, they'll walk over an invisible brick which will play a sound, and I only want the sound to play once and then stop and not play again. I'm very new to scripting, and I can't find any tutorials online.
I'm trying to make a sound play once, and then stop and not play again. Is this possible?
2 answers
What we use to only allow something to run once, or only allow it to run once every x amount of seconds, is known as "debounce". A debounce can be any if statement that the script has to run before executing the rest of it. For example, if you have a variable in the part, you can do this.
script.Parent.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") and script.Parent.HasPlayed.Value == false then
-- play the sound
script.Parent.HasPlayed.Value = true
--[[since this value is true, it will never make it through the if statement again
unless you change it back to false.]]
end
end)
You can also use debounce as a variable, however in your case the BoolValue would be much more effective if this is a single player game. The variable would look like this:
local debounce = false
script.Parent.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") and debounce == false then
--play sound
debounce = true
end
end)
Hope this helped.
1 comment
I still can't seem to get it to work. I'm not sure if I did it right or messed something up.
I usually do this for example:
script.Parent.Sound:Play() -- it only plays once
You would have to set this to loop to play over and over. It's actually very simple! All it does is play it and then do nothing.
2 comments
This would work if he wasn't using a touched event. His problem is that the event fires far too many times, most likely because he didn't have a debounce.
oh i usuallly use this for UI Buttons.
This discussion is preserved as it was. New answers, comments, and votes are closed.

3 comments
https://developer.roblox.com/en-us/articles/Debounce
To reply to your comment on my answer, Make sure that you have a variable in the invisible part named "HasPlayed", this script has to be a BoolValue. Make sure that the value is false when the game starts up. Other than that, tell me on my answer if there are any errors in the output of your studio.
Thank you very much, this was incredibly helpful, I got it to work!