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 sound stop after leaving a part?

I have a script to make a sound play when inside of an invisible part with no collide on but when you jump inside of it the sound plays twice while the first sound is already playing. You can see what I mean here. And I don't know how to end the sound playing if the user leaves the part it was in. Can anyone please help me with this? The script is the child of a part with a sound that is also a child of the part. I'm not that good at scripting btw.

debounce = false

script.Parent.Touched:connect(function(hit)
if not debounce then
debounce = true
if(hit.Parent:FindFirstChild("Humanoid")~=nil)then
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
local sound = script.Parent.Sound:Clone()
sound.Parent = player.PlayerGui
sound:Play()
wait(2)
end
debounce = false
end
end)

1 answer

✓ Accepted answer

You can use Sound.Ended:Wait() instead of wait(2) so we know exactly when the sound ends and when the debounce can become false.

debounce = false

script.Parent.Touched:connect(
    function(hit)
        if debounce == false then
            debounce = true
            if (hit.Parent:FindFirstChild("Humanoid") ~= nil) then
                local player = game.Players:GetPlayerFromCharacter(hit.Parent)
                local sound = script.Parent.Sound:Clone()
                sound.Parent = player.PlayerGui
                sound:Play()
                sound.Ended:wait()
                debounce = false
            end
        end
    end
)

Also, you can use TouchEnded so when the player gets out of the part, it will end the sound.



script.Parent.TouchEnded:Connect(
    function(hit)
            debounce = false
            local playergui = game.Players:GetPlayerFromCharacter(hit.Parent).PlayerGui
            if playergui.Sound then
                local sound = playergui.Sound
                sound:Destroy()
        end
    end
)

More information of TouchEnded and Sound.Ended:

https://developer.roblox.com/en-us/api-reference/event/Sound/Ended

https://developer.roblox.com/en-us/api-reference/event/BasePart/TouchEnded

PS: Touch Ended is very glitchy, so we can't really do anything bout that.

Accept answer if it worked.

2 comments

0

so should the touch ended be in a separate script as the child of the part or along with the script with the first script you sent

0

It should be in the same.

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