Syntax
Players.PlayerAdded:Connect(onPlayer)
for _, player in Players:GetPlayers() do
onPlayer(player)
endExamples
Handle new and existing players
Script in ServerScriptService. The seen guard avoids duplicate setup. The character handler is non-yielding here; larger systems should keep connection cleanup and character ownership explicit.
local Players = game:GetService("Players")
local seen = {}
local function onPlayer(player)
if seen[player] then return end
local function onCharacter(character)
print(player.Name, "spawned", character.Name)
end
seen[player] = player.CharacterAdded:Connect(onCharacter)
if player.Character then onCharacter(player.Character) end
end
Players.PlayerAdded:Connect(onPlayer)
Players.PlayerRemoving:Connect(function(player)
if seen[player] then seen[player]:Disconnect() end
seen[player] = nil
end)
for _, player in Players:GetPlayers() do onPlayer(player) endWait for your current character
LocalScript in StarterPlayerScripts. This obtains one current character for a one-time operation. To keep a feature working after respawn, move setup into CharacterAdded instead.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid", 10)
if humanoid and humanoid:IsA("Humanoid") then
print("Current health:", humanoid.Health)
endBest practices
- Use UserId for persistent identity; display names and usernames can change.
- Do not retain an old character reference across respawns.
- PlayerRemoving is a cleanup opportunity, not a guarantee that a network save will succeed.
Runtime & versions
Luau host; Roblox engine examples require Roblox Studio. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Luau documentation