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

How do I make a sound play on Touch event?

Asked by 4 years ago
Edited 4 years ago

Hello! I'm learning how to script, so sorry if i don't know things that are obvious, so I made a script in a part and here's the code

function Touch(tea)

tea = Touch.Parent:FindFirstChild("Humanoid")

if tea ~=nil then

  script.Parent.Music:Play()
  

end

end

3 answers

Log in to vote
0
Answered by 4 years ago

This is basically a sound region. For some people it might be hard but this can be solve easily. So add a part and let name this Sound1. Then add a script in the Sound1 and type this

Sound 1 script




local sound = "rbxassetid://413625451"--change the number for this script.Parent.Touched:Connect(function(hit) if hit.Parent:FindFirstChild("Humanoid") then local player = game.Players:GetPlayerFromCharacter(hit.Parent) game.ReplicatedStorage.PlayMusic:FireClient(player,sound) end end)

then go to ReplicatedStorage and add a RemoteEvent and name it PlayMusic

then go to StarterGui and insert a sound but don't put any id in it. Once you insert the sound you need to add a local script in the sound or music and type this.

Sound Music local script that is in StarterGui

-- Must be inside the Sound in StarterGui

game.ReplicatedStorage.PlayMusic.OnClientEvent:Connect(function(sound) -- PlayMusic is the name of the RemoteEvent. Change it if you have a different name.
    if script.Parent.SoundId ~= sound then
        script.Parent:Stop()
        script.Parent.SoundId = sound
        script.Parent:Play()
    end
end)
0
Thanks, it worked. And im actually surprised you have to add so much stuff to just play a sound in a part. lunar_maker 2 — 4y
Ad
Log in to vote
1
Answered by 4 years ago
Edited 4 years ago

fix that code to:

function Touch(tea)

Hum = tea.Parent:FindFirstChild("Humanoid") -- Your parameter is tea, not hit the parameter here is the part that touched 

if tea ~=nil then

script.Parent.Music:Play()
end

end
Log in to vote
0
Answered by 4 years ago
Edited 4 years ago

Your error is that you are not calling the function. A function is a segment of code only runs when you call it through code(either through events or just inlcuding the name of the function with parantheses when needed) So this is how I would do what you were asking

local part= script.Parent


part.Touched:Connect(function(hit) -- another error is that in your case, you're using tea as a
--parameter, but the event of the function includes the part that touched it, and you're using the ----parameter tea in the wrong way. So I am using hit to find the humanoid, and if there is, music ----will play.
    if hit.Parent:FindFirstChild("Humanoid") then
    part.Music:Play()
    end
end
0
Also, sorry for the weird looking comments, the website just kind of formatted it in the wrong way. Cyroxite 46 — 4y

Answer this question