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

How to have music stop playing when you step off the block?

Asked by
Vanada 0
10 years ago

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)

2 answers

Log in to vote
2
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
10 years ago

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)
0
You don't even need the variable, unless you are using it somewhere else. Gamenew09 180 — 10y
0
It prevents the Touched event from firing a whole bunch of times, decreasing lag. Perci1 4988 — 10y
Ad
Log in to vote
-1
Answered by 10 years ago

script.Parent.MusicName:Stop()

Answer this question