I have block with music in it. Once you touch it the music plays. I want the music to stop once you step off the block. How would I edit this to make it stop once UnTouched,
1 | game.Workspace.LobbyMusic.Touched:connect( function (obj) |
2 | if obj.Parent:FindFirstChild( "Humanoid" ) ~ = nil then |
3 | script.Parent:Play() |
4 | obj.Parent.Humanoid.Died:connect( function () |
5 | script.Parent:Stop() |
6 | end ) |
7 | end |
8 | end ) |
First of all, don't use game.Workspace
, even though it's technically down to preference, workspace
is much shorter and easier to use.
Second, you should tab your code, this makes it easier to read.
Third, you don't need the ~= nil
on line 2, it's just redundant.
Fourth, there is an event called TouchEnded()
, this fires when something moves off a part.
In context it would look like this...
01 | workspace.LobbyMusic.Touched:connect( function (obj) |
02 | local Model = obj.Parent |
03 | if Model:FindFirstChild( "Humanoid" ) then |
04 | script.Parent:Play() |
05 | Model.Humanoid.Died:connect( function () |
06 | script.Parent:Stop() |
07 | end ) |
08 | end |
09 | end ) |
10 | workspace.LobbyMusic.TouchEnded:connect(fucntion(obj) -- Fires when a part moves off |
11 | local Model = obj.Parent -- The parent of the part that touched workspace.LobbyMusic |
12 | if Model:FindFirstChild( "Humanoid" ) then -- Checks if Model is a player |
13 | script.Parent:Stop() -- Stops the music |
14 | end |
15 | end ) |
I hope this helps! (I've also tabbed code for you)
Also if you want to click a part for music add a ClickDetector then add sound paste the ID in there, then add a script which is:
1 | script.Parent.ClickDetector.MouseClick:Connect( function () |
2 | script.Parent.Sound:Play() |
3 | end ) |
This script stops the music!
1 | script.Parent.ClickDetector.MouseClick:Connect( function () |
2 | script.Parent:Stop() |
3 | end ) |