✓ Accepted answer
You should really check if the person who touched it is truly a player, since the Touched even is triggered by any part touching it. However, to make it stop when the touch ends, use the TouchEnded event. Just remember that it may be slightly glitchy if multiple players are touching it at once.
A few more small errors,, you do not have an end to close the if statement on line 02, and the parenthesis on line 05 is not needed. You also forgot your connection line.
I'm going to use anonymous functions just because it's my preferred style. You don't have to if you don't want to.
local touching = false
script.Parent.Touched:connect(function(hit)
if game.Players:GetPlayerFromCharacter(hit.Parent) and not touching then
touching = true
script.Parent.GHZMusic2:Play()
end
end)
script.Parent.TouchEnded:connect(function(hit)
if game.Players:GetPlayerFromCharacter(hit.Parent) then
touching = false
script.Parent.GHZMusic2:Pause()
end
end)
2 comments
You don't even need the variable, unless you are using it somewhere else.
It prevents the Touched event from firing a whole bunch of times, decreasing lag.