This function returns the
Player associated with the given
nil if one cannot be found. It is equivalent to the following function:
local function getPlayerFromCharacter(character) for _, player in pairs(game:GetService("Players"):GetPlayers()) do if player.Character == character then return player end end end
This method is often used when some event in player’s character fires (such as their
Humanoid/Died|dying). Such an event might not directly reference the Player object, but this method provides easy access. The inverse of this function can be described as getting the Character of a Player. To do this, simply access the Character property.
A character instance that you want to get the player from.
A player instance corresponding to the character passed as input.
Player Part Touch Detection
When pasted into a
Script within a
BasePart|Part, this code sample detects when a
Player touches the part and prints their name.
local Players = game:GetService("Players") local part = script.Parent local function onTouched(part) local player = Players:GetPlayerFromCharacter(part.Parent) if not player then return end print(player.Name .. " pressed me!") end part.Touched:Connect(onTouched)
local character = game.Workspace.Player local player = game.Players:GetPlayerFromCharacter(character) if player then print("Player is " .. player.Name) else print("Player doesn't exist!") end