Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I make a sound play on Touch event?

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

✓ Accepted answer

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)

1 comment

0

Thanks, it worked. And im actually surprised you have to add so much stuff to just play a sound in a part.

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

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

1 comment

0

Also, sorry for the weird looking comments, the website just kind of formatted it in the wrong way.

This discussion is preserved as it was. New answers, comments, and votes are closed.