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)
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.