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

If player has already touched the block, the sound wont play?

I made a script that once the player touches the brick, a sound plays.

script.Parent.Touched:Connect(function()
	game.Workspace.THEPART.WinSound:Play()
end)

But then, I wanted to make it so that if the same player has already touched the block, the block won't play the sound again. But if a different player HASN'T touched the block, and he/she touches it, it will play the sound. I didn't know how to put that in code, so some help would be great!

1 comment

0

is there any errors?

1 answer

One good way to do this is to save the players who have touched the part and not play the sound if they're in the dictionary. like this. (btw I'm saving it by their user id):

local players = gam
local playersWhoTouched = {}
script.Parent.Touched:Connect(function(otherPart)
    if part.Parent:IsA("Model") and players:GetPlayerFromCharacter(part.Parent) then -- were getting the player if the part is in a charcter
	local plyr = players:GetPlayerFromCharacter(part.Parent)
	if not playersWhoTouched[plyr.UserId] then -- heres the part where we make sure they haven't already touched it
		-- here we will record that the player touched it
		playersWhoTouched[plyr.UserId] = true
    		game.Workspace.THEPART.WinSound:Play()
	end
end)

This will work but the problem is as players join touch the part and leave, its possible large numbers of user ids could accumulate in the dictionary, so for the sake of this situation we will remove them from the table when they leave the server like so:

local players = gam
local playersWhoTouched = {}
script.Parent.Touched:Connect(function(otherPart)
    if part.Parent:IsA("Model") and players:GetPlayerFromCharacter(part.Parent) then -- were getting the player if the part is in a charcter
	local plyr = players:GetPlayerFromCharacter(part.Parent)
	if not playersWhoTouched[plyr.UserId] then -- heres the part where we make sure they haven't already touched it
		-- here we will record that the player touched it
		playersWhoTouched[plyr.UserId] = true
    		game.Workspace.THEPART.WinSound:Play()
	end
end)
players.PlayerRemoving:Connect(function(plyr) 
	playersWhoTouched[plyr.UserId] = nil -- remove it from the dictionary if they leave so as not to waste memory
end)

There you go. If you need further explanation, ask in the comments.

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