Cannot play sounds for client only

Hi There!

I want to play a sound that only the player who touched a Part can hear.
When a player touches a part, the sound plays for every player on the server instead of playing for that one player who touched the Part

This is the local script

workspace.Part.Touched:Connect(function()

game.SoundService.Sound:Play()

end)

I’ve tried putting the Sound and LocalScript in PlayerGui, in the player’s character, in the workspace
I’ve tried PlayLocalSound() function but nothing worked

local SoundService = game:GetService("SoundService")
local function playLocalSound(soundId)
	
	local sound = Instance.new("Sound")
	sound.SoundId = soundId
	
	SoundService:PlayLocalSound(sound)
	
	sound.Ended:Wait()
	sound:Destroy()
end


workspace.Part.Touched:Connect(function()
	playLocalSound("rbxassetid://1837461008")
end)

You don’t do any verification on who actually touched the part, because the event is made locally for each player, anyone could touch the part and it wont fire for every event for every player.

A simple fix would be to get the player from the Touched event using what the event gives us and GetPlayerFromCharacter, then we just compare if the player that touched the part is equal to your localplayer, and if it is, paly the sound

local Players = game:GetService("Players")

workspace.Part.Touched:Connect(function(hit)
	local player = Players:GetPlayerFromCharacter(hit.Parent)
	if player ~= Players.LocalPlayer then
		return
	end
	playLocalSound("rbxassetid://1837461008")
end)
1 Like