How To Add A Gui For All Players In A Table?

I want to learn how to access a array of players from a table, and for example I want to add a gui into each player’s PlayerGui.

script.Parent.Touched:Connect(function(TouchedPart)
	if TouchedPart.Parent:FindFirstChild("Humanoid") and _G.amount <= 12 then 
		local Character = TouchedPart.Parent
		local player = game.Players:GetPlayerFromCharacter(Character)
		local AlreadyInTable = false
		for _,OtherPlayer in next,_G.PlayersToTeleport  do
			if OtherPlayer == player then
				AlreadyInTable = true
			end
		end
		if not AlreadyInTable then
		table.insert(_G.PlayersToTeleport ,player)

---How do I access the array of players?

Here is what I came up with, just runs through the table and compares players in the game to players in the table. If they are in the table put the gui into the player.

for i,v in pairs(game.Players:GetPlayers()) do
	local playerGood = false 
	
	for i = 1,#_G.PlayersToTeleport do
		if v == _G.PlayersToTeleport[i] then
			playerGood = true
		end
	end
	
	if playerGood == true then
		local screenGui = SCREENGUI:Clone()
		screenGui.Parent = v.PlayerGui
	end
end

And well to answer your question, the best way I do it [ as you can see in the code above ] I just run through using a for i loop . And then access the index. Not sure if there is another way.

To access an array of all the players you can use game.Players:GetPlayers() this will return a table of all currently connected players. You can then loop through the table and do what you would like with each player. You could also get a table of players by using game.Players:GetChildren() but the other way gives all Player objects.

1 Like

GetPlayers() and GetChildren() are essentially the same thing. They both return an array of player objects. GetChildren() just will return all children of Players even non-player objects. That is why they added in GetPlayers() to prevent that.