Users and Players

*此內容很快就會推出您所選的語言版本。

When a user joins an experience, Roblox represents them as a Player in the data model. The Player object contains information about the user that's universal across experiences, such as their username, friend list, saved avatar character, and Roblox membership type, as well as properties, methods, and events that affects the user's lifecycle between joining and leaving your experience.

The Players service contains all the Player instances in an experience. Each Player object represents a user in the experience, and it parents four important containers that you can use to customize a user's experience: Backpack, StarterGear, PlayerGui, and PlayerScripts.

Lifecycle

Client and server-side scripts can both connect to the Players.PlayerAdded and Players.PlayerRemoved events to perform actions in response to the lifecycle of a Player object. They can also connect to the Player.CharacterAdded, Player.CharacterRemoving, and Humanoid.Died events to perform gameplay-related actions for when the character spawns, despawns, and dies.

Use Scripts to access server-related services, such as a data store to retrieve and save data when a user joins or leaves. Use LocalScripts if the client needs to create and remove gameplay instances tied to the new user, such as a GUI display for the user's stats on a custom leaderboard.

User Joining

When a client connects to an experience, its associated Player object clones to the Players service. The Players.PlayerAdded represents users joining the experience. Some example use-cases include loading user data, assigning teams, and changing a user's character's clothing. The Players.PlayerAdded event passes the Player object of the user who joins, which you can use when calling other functions, such as data store and RemoteEvent objects.

Loading User Data on Join

To load a user's data when they join an experience, use the Players.PlayerAdded event in a Script. The following example Script listens to the event and attempts to retrieve a user's data using their user ID as the datastore key. After successfully retrieving the user data, you can use it to load the user's progress and stats.


local DataStoreService = game:GetService("DataStoreService")
local playerDataStore = DataStoreService:GetDataStore("PlayerData")
game:GetService("Players").PlayerAdded:Connect(function(player)
local userId = player.UserId
-- Read data store key
local getSuccess, currentData = pcall(function()
return playerDataStore:GetAsync(userId)
end)
if getSuccess then
print(currentData)
end
-- Do further actions with currentData
end)

User Leaving

When a client disconnects from an experience, the server destroys its associated Player object from the Players service. The Players.PlayerRemoving event represents users leaving the experience. Some example use-cases include saving user data, removing their stats from a scoreboard, and destroying any of their models, such as their house. The Players.PlayerRemoving event passes the Player object of the user who leaves, which you can use when calling other functions, such as data store and RemoteEvent objects.

Notice that the event is called Player.PlayerRemoving, not Player.PlayerRemoved, because "removed" would imply that the Player object is already removed and is therefore inaccessible to scripts.

Saving User Data on Leave

To save a user's data when they leave an experience, use the Players.PlayerRemoving event in a Script. The following example Script listens to the event and attempts to save a user's data using their user ID as the data store key.

Script in ServerScriptService

local DataStoreService = game:GetService("DataStoreService")
local playerDataStore = DataStoreService:GetDataStore("PlayerData")
game:GetService("Players").PlayerRemoving:Connect(function(player)
local userId = player.UserId
-- Get the player's data state in the game
local currentData = getCurrentData(player)
-- Save to data store
local setSuccess, errorMessage = pcall(function()
playerDataStore:SetAsync(userId, currentData)
end)
if not setSuccess then
warn(errorMessage)
end
end)

Character Spawning

A user's Player.Character model represents their avatar. By default, Player.CharacterAutoLoads is true, and a user's character model automatically spawns when they join the experience. If Player.CharacterAutoLoads is false, then you need to call Player:LoadCharacter() to manually spawn the character.

When a user's Player.Character spawns, Scripts and LocalScripts in StarterCharacterScripts clone into the character model and the Player.CharacterAdded event fires. The Player.CharacterAdded event passes the new character model to any event listeners, which you can use to find the character's Humanoid object and modify its behavior. For example, you can use Humanoid:ApplyDescription() to change the outfit of the avatar and Humanoid.WalkSpeed or Humanoid.JumpHeight to modify the avatar's movement.

Character Despawning

When the player's Humanoid dies, its body parts fall to the ground and the Humanoid.Died event fires. The server automatically removes the character model and any scripts inside it after amount of time that the Players.Respawntime property determines. You can use the Player.CharacterRemoving event to reset other objects associated with the character, such as the network ownership of a vehicle they were driving.

Counting Player Deaths

You can use the Humanoid.Died event to handle scoring for a kill or create a custom ragdoll model. The following Script connects to Player.CharacterAdded to retrieve each user's character model, then connects to the character's Humanoid object. When the humanoid's Humanoid.Died event fires, the script increments the number of times the user's humanoid has died and outputs that number.

Script in ServerScriptService

game:GetService("Players").PlayerAdded:Connect(function(player)
local deaths = 0
player.CharacterAdded:Connect(function(character)
local humanoid = character:WaitForChild("Humanoid")
humanoid.Died:Connect(function()
deaths += 1
print(player.Name .. " death count: " .. deaths)
end)
end)
end)

Banning Users

To ensure civility and fair play in your experiences, you can ban users who violate your experience rules and community guidelines. You can modify ban durations, ban messages, and even extend bans to potential alternate accounts. When using this feature, you must also follow guidelines for banning and messaging.

For implementation and usage instructions, see Players.BanAsync.

Ban Guidelines

When implementing bans in your experience, adhere to the following guidelines:

  • Experience rules must not contradict Roblox's Community Standards and Terms of Use.
  • Creators must clearly state their experience rules somewhere accessible to all users.
  • Creators must apply their experience rules fairly and not arbitrarily target certain users.
  • Users can appeal to creators directly if they believe their ban was incorrect.
    • Roblox will not mediate these appeals, unless the user believes the creator's experience rules or enforcement of their rules violate the Community Standards.
  • Roblox can moderate an experience if there is reason to believe that a creator's experience rules or enforcement of their rules violate the Community Standards.

Message Guidelines

When a user is banned, they receive an error modal displaying information such as the ban length and reason. In the text-filtered message, you can include additional information such as appeal or contact information as long as you meet Roblox's Community Standards.

For example, in your ban messages, you are allowed to reference brand names and platforms:

  • "Visit the Discord in my group/experience page"
  • "Message me on Twitter or X"

Mentions of personal information or direct links are not allowed in this message field. This includes posting a specific username or handle, or providing a direct link to a Discord server or X account.

Containers

The Player object stores several important containers:

Backpack

The Player.Backpack container stores the user's inventory. The Tool objects in a user's Backpack display in their inventory at the bottom of their screen. If a user selects a Tool from the inventory, they equip it, and it moves from the Player.Backpack to the Player.Character.

When a user's Player.Character spawns, the contents of the StarterPack service and their Player.StarterGear clones to their Player.Backpack. When the character dies, the client destroys their Backpack and replaces it with a new one.

The Backpack also stores and runs Scripts and LocalScripts that the client and server can both access.

Roblox provides an interface for a player to access their Backpack and inventory at the bottom of the screen. To disable the default Roblox backpack GUI and replace it with your own, call StarterGui:SetCoreGuiEnabled() in a LocalScript. For more information, see StarterGui.

StarterGear

The StarterGear container clones its contents to the user's Player.Backpack when its character spawns. Additionally, if your place permits gear and a user owns gear, the Tool objects of their gear clone to their Player.StarterGear when they spawn.

Unlike StarterPack, Player.StarterGear isn't a service but rather a child of each Player object, so its contents are user-specific. Each user can have different Tool objects within their Player.StarterGear. To use Player.StarterGear, enable Gear in your experience's settings page under Permissions. On the permissions page, you can enable by gear by its type. To disable gear, deselect its type.

Always test games after adding Gear to them to check that users can't easily abuse them there. Gear includes Script objects and allows the player to perform actions that you might not consider. For example, a navigational gear might allow the player to access a part of the map that you don't want them to. Weapons allow players with gear to damage other players, possibly without retribution or retaliation.

PlayerGui

The PlayerGui container stores objects that create the player's GUI. If a ScreenGui is a descendant of a PlayerGui, then any GuiObject inside the ScreenGui displays on the player's screen. Any LocalScript runs when it clones to PlayerGui. When the player's Player.Character spawns for the first time, all of the contents of StarterGui automatically copy into the player's PlayerGui.

If Players.CharacterAutoLoads is set to false, the character doesn't spawn, and StarterGui contents don't copy over until Player:LoadCharacter() is called. If StarterGui.ResetPlayerGuiOnSpawn is set to true, every time the player's character respawns, all of the contents of that player's PlayerGui are cleared and replaced with the contents of StarterGui.

PlayerScripts

When a user joins the experience, the contents in StarterPlayer.StarterPlayerScripts container clone to PlayerScripts. Any LocalScripts and ModuleScripts run when they clone.

Unlike the Backpack and PlayerGui containers, the PlayerScripts container isn't accessible to the server, and a user's PlayerScripts container doesn't reset when their character dies and respawns. Server-side Script objects also don't run when parented to PlayerScripts. The PlayerScripts container is useful for scripts that aren't tied to a user's character life cycle, such as the general chat system or player input controls.