PcoWSkbVqDnWTu_dm2ix
Collapse Sidebar

GetPlayers

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 function onPlayerAdded(player)
	print("Player: " .. player.Name)
end

for _, player in pairs(Players:GetPlayers()) do
	onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)

Returns

Return Type Summary

A table containing all the players in the server.


Code Samples


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, onPlayerSpawned and onPlayerAdded. It calls these functions for players/characters already in the game, in case the script runs after players already arrive.