Playing a sound for 1 player only

Hello and thank you for reading this :slight_smile:

I’m kinda new to scripting and I’ve made a script where when you touch a part a sound plays. However, I’ve noticed that the sound plays for everyone when I just want the sound to play for the player that touched the part.

Here’s the script I have:

local sound = script.Parent.Sound
local play = false

script.Parent.Touched:Connect(function(hit)
	if hit.Parent:FindFirstChild("Humanoid") and play == false then
		play = true
		sound:Play()
		wait(1)
		play = false
		sound:Stop()
	end
end)

Any help would be greatly appreciated on how I can accomplish this!

You would have to play the sound locally (so run the sound script in a local script). If you need the rest to be in a server script then you could use a remote event to fire from the server to the local side to have a local script play locally.

2 Likes

You can try to use it.

local sound = Instance.new("Sound")
sound.SoundId = "rbxassetid://ID"

sound.Parent = game.Players.LocalPlayer.PlayerGui
sound:Play()

Thanks for the help, could you please give me a simple example of how I would do this? Again, a bit new to scripting, sorry haha

I would recommend checking the documentation out. It has examples and may explain it better then me just giving out code.

1 Like

You would have an object called a “RemoteEvent” in ReplcatedStorage, then have the script say this:

script.Parent.Touched:Connect(function(hit)
	if hit.Parent:FindFirstChild("Humanoid") and play == false then
		play = true
		--this is where im changing the script
        game.ReplicatedStorage.Event:FireClient(hit.Parent.Parent.Name)
        --this is firing it only for one client, the player who touched it
        wait(1)
		play = false
	end
end)

And then in a localscript, have this:

game.ReplicatedStorage.OnClientEvent:Connect(function()
     --im going to assume theres a var called sound
     sound:Play()
     wait(1)
     sound:Stop()
end)

That should be all, let me know if it works!

1 Like

Wow! Thank you so much for this response!! Just a question, where would I put the local script? In the part the player touches? Or somewhere else?

Also, in the local script, it’s giving me this error, do I need to add an extra bracket somewhere?
error

For your first question, you can really put it anywhere, but the cleanest way to organize your scripts is to put it in CharacterScripts>>PlayerScripts

For your second question: I forgot a bracket, the beginning of your script should look like this:

game.ReplicatedStorage.OnClientEvent:Connect(function()--closed brackets
1 Like

Ah, got it. Thank you so much for your help, I really appreciate it :DD

No problem! If my solution helped you, then click the solution button under my reply, so people know that this topic is solved!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.