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

How do i make a script to play a sound once?

i am trying to make it when a player touches a part it played a sound once, and the sound can't be played again until they leave it. and if they touch it again, it will play. This is what i thought of, and it doesn't seem to work. Any suggestions?

local debounce = false

script.Parent.Touched:connect(function(hit1)
	if debounce == false then
		script.Parent.Sound:Play()
		debounce = true
	end
end)

script.Parent.TouchEnded:connect(function(hit2)
	
debounce = false
	
end)

i do not want the sound to be played locally to the player.

1 answer

✓ Accepted answer

If you don't want to sound to be played locally to the player, then use a ServerScript.

local debounce = false

script.Parent.Touched:connect(function(hit1)
    if not debounce then
	debounce = true
        script.Parent.Sound:Play()
        wait(3) --how long you want before it can be touched and played again
	debounce = false
    end
end)

Let me just run through quickly on what you did wrong.

local debounce = false

script.Parent.Touched:connect(function(hit1)
    if debounce == false then
        script.Parent.Sound:Play()
        debounce = true 
    end
end)

Here, you placed debounce = true and debounce = false in the wrong place.

Btw, idk why you put hit1 in the parenthesis. Unless you're trying to identify that it's a player, I suggest that you do this:

local debounce = false

script.Parent.Touched:connect(function(hit1)
local character = hit1.Parent
    if not debounce then
	debounce = true
	if character and character:findFirstChild("Humanoid") then
        script.Parent.Sound:Play()
	end
        wait(3) --how long you want before it can be touched and played again
	debounce = false
    end
end)

What that does is that it looks for "Humanoid" in the character.

Hope this helps!

EDIT(because asked):

local debounce = false

script.Parent.Touched:connect(function(hit1)
local character = hit1.Parent
    if not debounce then
	debounce = true
	if character and character:findFirstChild("Humanoid") then
        script.Parent.Sound:Play()
	end
        wait(3) --how long you want before it can be touched and played again
	debounce = false
    end
end)

script.Parent.TouchEnded:connect(function()
	--your code
end)

4 comments

0

how do i make it so at line 10 it has to wait until the player is not touching the part?

0

added an extra part because you asked, try that

0

added an extra part because you asked, try that!

0

had to manipulate a bit, but eventually worked. thanks! i found out the part that they had to touch first was too small. so i had to make another one that is bigger

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