Trouble with playing a sound once to the local player!

I wanted the block to play a sound to the local player, and I don’t know how to make it so when the player touched it again, the block will detect if the local player already has the sound playing or not.
If the player already has a sound playing, it won’t play it again.

But if another player touched the part, THAT player will hear their own sound. How do I do that from hear? (Also, I’m a beginner, so I have no idea what to do)

script.Parent.Touched:connect(function(hit)
	if hit.Parent:FindFirstChild("Humanoid") then
		local player = game.Players:GetPlayerFromCharacter(hit.Parent)
		local sound = script.Parent.Sound:Clone()
		sound.Parent = player.PlayerGui
		sound:Play()
	end
end)
script.Parent.Touched:connect(function(hit)
	if hit.Parent:FindFirstChild("Humanoid") then
		local player = game.Players:GetPlayerFromCharacter(hit.Parent)
		if not player.PlayerGui:FindFirstChild("SoundEffect") then --// Check if sound doesnt exist
			local sound = script.Parent.Sound:Clone()
			sound.Name = "SoundEffect"
			sound.Parent = player.PlayerGui
			sound:Play()
			sound.Ended:Wait() --// Wait for the sound to end
			sound:Destroy() --// Destroy the sound after it ended
		end
	end
end)
1 Like

Thank you so much! You’re a life saver!

A simpler solution I always love to use is :Stop() :Play()
Also if your sound is not loaded on time you may want to check

if sound.IsLoaded == false then
  sound.Loaded:Wait()
end
1 Like

thanks anyway though! But I wouldn’t know how to program that in the script

All you have to do if you want to program that is:

  • for the :Stop you just put a line saying sound:Stop() above the sound:Play() so it resets the sound before it plays it
  • for the loaded check, it waits until the sound loads if it isn’t loaded already, the technical term for that is yielding, basically before you play the sound, paste the if check above

don’t forget to change sound with the variable of your sound object

I see that you’re a new scripter, but seem to want to learn more so if there’s anything you don’t know yet feel free to ask!

1 Like

That’s smart! Thank you for the tip!

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