Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How do I make sound stop after leaving a part?

Asked by 4 years ago
Edited 4 years ago

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

Log in to vote
0
Answered by
raid6n 2196 Moderation Voter Community Moderator
4 years ago
Edited 4 years ago

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.

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 alialan626 25 — 4y
0
It should be in the same. raid6n 2196 — 4y
Ad

Answer this question