I'm making a script for when you touch a block and music plays. But how do you add the lines of code that have the music turn off when you step off of it?
function onTouched(part) if part.Parent ~= nil then script.Parent.GHZMusic2:Play() ??? end)
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 --Makes sure it's a player and no one's already touching it. touching = true script.Parent.GHZMusic2:Play() end end) --This parenthesis is needed to close 'connect' on line 02, but only because this is an anonymous function. script.Parent.TouchEnded:connect(function(hit) if game.Players:GetPlayerFromCharacter(hit.Parent) then --No need to check if it touched == true, since it will be true if the TouchEnded event is fired. touching = false script.Parent.GHZMusic2:Pause() end end)