Second player printing twice?

Hey I am trying to have a table with players in the game, when I join it the table works just fine, when my friend joins it adds their name to the table twice

local PlayerTable = {}
local AmountOfPlayers = 0

game.Players.PlayerAdded:Connect(function(player)
	AmountOfPlayers = AmountOfPlayers + 1
	for i,v in pairs(game.Players:GetChildren()) do
		table.insert(PlayerTable, player)
	end
	print(AmountOfPlayers)
	print(unpack(PlayerTable))
end)

How will I have the other players only add their name to the table once?

1 Like

Instead of adding ever single Player to the table again when a Player is connected, just add the Player that joined.


game.Players.PlayerAdded:Connect(function(player)
	AmountOfPlayers = AmountOfPlayers + 1
	
	table.insert(PlayerTable, player)
	
	print(AmountOfPlayers)
	print(unpack(PlayerTable))
end)

Otherwise, you will end up with a multitude of duplicates.

3 Likes

Awesome thanks for the explanation

1 Like

More fundamentally, using an array like this allows duplicate entries of the same player.
You should not use table.insert() for this purpose. The key in your table ought to be
a string representation of Player.UserId and your value be whatever data you want
to associate with the player.