This method returns a table of all presently connected
Player. It functions the same way
Instance/GetChildren would except that it only returns Player objects. It functions similarly to
Instance/GetChildren when called on
Players. 0 When used in conjunction with a for-loop, it is useful for iterating over all players in a game.
Players = game:GetService("Players") for i, player in pairs(Players:GetPlayers()) do print(player.Name) end
Scripts that connect to
Players/PlayerAdded are often trying to process every Player that connects to the game. This method is useful for iterating over already-connected players that wouldn’t fire
Players/PlayerAdded|PlayerAdded. Using this method ensures that no player is missed!
local Players = game:GetService("Players") local onPlayerAdded(player) print("Player: " .. player.Name) end for _, player in pairs(Players:GetPlayers()) do onPlayerAdded(player) end Players.PlayerAdded:Connect(onPlayerAdded)
A table containing all the players in the server.
Give Sparkles to Everyone
This code sample listens for players spawning and gives them Sparkles in their head. It does this by defining two functions,
onPlayerAdded. It calls these functions for players/characters already in the game, in case the script runs after players already arrive.
local Players = game:GetService("Players") local function onCharacterAdded(character) -- Give them sparkles on their head if they don't have them yet if not character:FindFirstChild("Sparkles") then local sparkles = Instance.new("Sparkles") sparkles.Parent = character:WaitForChild("Head") end end local function onPlayerAdded(player) -- Check if they already spawned in if player.Character then onCharacterAdded(player.Character) end -- Listen for the player (re)spawning player.CharacterAdded:Connect(onCharacterAdded) end -- Iterate over each player already connected -- to the game using a generic for-loop for i, player in pairs(Players:GetPlayers()) do onPlayerAdded(player) end -- Listen for newly connected players Players.PlayerAdded:Connect(onPlayerAdded)