Player

Hiển Thị Bản Đã Lỗi Thời

*Nội dung này được dịch bằng AI (Beta) và có thể có lỗi. Để xem trang này bằng tiếng Anh, hãy nhấp vào đây.

Một đối tượng Người chơi là một khách hàng hiện đang kết nối.Các đối tượng này được thêm vào dịch vụ Players khi một người chơi mới kết nối, sau đó được xóa khi họ cuối cùng kết nối từ máy chủ.

Thuộc tính Instance.Name phản ánh tên người dùng của người chơi.Khi lưu thông tin về một người chơi, bạn nên sử dụng Player.UserId của họ vì có thể một người chơi có thể thay đổi tên người dùng của họ.

Có một số phương pháp tương tự trong dịch vụ để làm việc với các đối tượng Người chơi. Sử dụng chúng vượt qua các phương pháp tương ứng của chúng:

  • Bạn có thể nhận được một bảng các đối tượng Người chơi hiện tại bằng cách sử dụng Players:GetPlayers() ; một lần nữa, sử dụng nó thay cho Instance:GetChildren() .
  • Để phát hiện sự thêm của các đối tượng Người chơi, được khuyến nghị sử dụng sự kiện Players.PlayerAdded (thay vì Instance.ChildAdded trên dịch vụ Players).
  • Tương tự, bạn có thể phát hiện việc xóa các đối tượng Người chơi bằng cách sử dụng , được kích hoạt chỉ trước khi Người chơi bị xóa (thay vì được kích hoạt sau khi)Điều này là quan trọng nếu bạn đang lưu thông tin về người chơi có thể bị xóa hoặc dọn sạch trong quá trình xóa.

Mẫu mã

Ví dụ mã này cho thấy việc tạo các giá trị chỉ số bảng xếp hạng trong UI danh sách người chơi mặc định của Roblox.Nó tạo ra một leaderstat "Điểm" bắt đầu tại 0.

Leaderstats là gì

local Players = game:GetService("Players")
local function onPlayerAdded(player)
-- Tạo một thùng chứa cho leaderstats
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
-- Tạo một giá trị leaderstat
local vScore = Instance.new("IntValue")
vScore.Name = "Score"
vScore.Value = 0
vScore.Parent = leaderstats
-- Thêm vào người chơi (hiển thị nó)
leaderstats.Parent = player
end
Players.PlayerAdded:Connect(onPlayerAdded)

Tóm Tắt

Thuộc Tính

  • Chỉ Đọc
    Không Sao Chép
    Đọc Song Song

    Mô tả tuổi tài khoản của người chơi trong các ngày.

  • Đọc Song Song

    Xác định xem nhân vật của một người chơi sử dụng thiết bị di động có tự động nhảy lên khi va chạm với chướng ngại vật hay không.

  • Khoảng cách tối đa mà máy ảnh của người chơi được phép phóng to.

  • Khoảng cách tối thiểu mà camera của người chơi được phép phóng to.

  • Đọc Song Song

    Thay đổi chế độ của camera thành người thứ nhất hoặc người thứ ba.

  • Xác định xem liệu sự xuất hiện của nhân vật sẽ được tải khi người chơi xuất hiện. Nếu là false, người chơi sẽ xuất hiện với một sự xuất hiện mặc định.

  • Đọc Song Song

    Một Model được kiểm soát bởi người chơi chứa một Humanoid , các bộ phận cơ thể, các kịch bản và các đối tượng khác.

  • Xác định ID người dùng của tài khoản mà nhân vật xuất hiện của nó được sử dụng cho một người chơi character .

  • Xác định cách camera mặc định xử lý các đối tượng giữa camera và người chơi.

  • Xác định chế độ di chuyển máy ảnh của người chơi khi sử dụng phiên bản máy tính của Roblox.

  • Xác định chế độ di chuyển nhân vật của người chơi khi sử dụng phiên bản máy tính của Roblox.

  • Đọc Song Song

    Xác định xem người chơi có thể bật/tắt khóa chuột không.

  • Xác định chế độ di chuyển máy ảnh của người dùng khi sử dụng thiết bị cảm ứng.

  • Xác định chế độ di chuyển nhân vật của người chơi khi sử dụng thiết bị cảm ứng.

  • Đọc Song Song

    Tên hiển thị của UserId liên quan đến Player.

  • Chỉ Đọc
    Không Sao Chép
    Đọc Song Song

    Mô tả ID người dùng của người chơi đã theo dõi vào một trò chơi bởi một người chơi.

  • Bảo Mật Không Thể Tiếp Cận
    Đọc Song Song

    Liệu trò chơi bên khách của người chơi hiện đang bị tạm dừng.

  • Đọc Song Song

    Chỉ ra nếu một người chơi có một Huy hiệu đã xác minh.

  • Đặt khoảng cách mà người chơi này sẽ nhìn thấy các thanh sức khỏe của các Humanoid khác. Nếu đặt thành 0, các thanh sức khỏe sẽ không được hiển thị.

  • Ẩn
    Chỉ Đọc
    Không Sao Chép
    Đọc Song Song

    Thuộc tính này hiển thị ID khu vực mà người chơi địa phương đã đặt cho tài khoản Roblox của họ.

  • Chỉ Đọc
    Không Sao Chép
    Đọc Song Song

    Mô tả loại thành viên của tài khoản.

  • Đọc Song Song

    Đặt khoảng cách mà người chơi này sẽ nhìn thấy tên của các Humanoid khác. Nếu được đặt thành 0, các tên sẽ được ẩn.

  • Đọc Song Song

    Xác định xem người chơi có ở trong một đội cụ thể hay không.

  • Ẩn
    Không Sao Chép
    Bảo Mật Roblox
    Đọc Song Song

    Một nhận dạng duy nhất của bên tham gia mà một Player thuộc về.

  • Đọc Song Song

    Đặt phần tập trung sao chép xung quanh.

  • Nếu được đặt, người chơi sẽ hồi sinh tại điểm SpawnLocation đã cho.

  • Bảo Mật Roblox
    Đọc Song Song
  • Không Sao Chép
    Đọc Song Song

    Xác định đội mà một Người chơi được liên kết.

  • Đọc Song Song

    Xác định đội mà một Người chơi được liên kết.

  • Chỉ Đọc
    Không Sao Chép
    Bảo Mật Kịch Bản Roblox
    Đọc Song Song
  • Đọc Song Song

    Một số nhận dạng duy nhất được gán cho tất cả các tài khoản người dùng.

Phương Pháp

  • Loại bỏ tất cả các phụ kiện và các đối tượng xuất hiện nhân vật khác từ nhân vật của người chơi.

  • Trả về khoảng cách giữa đầu nhân vật và điểm Vector3 đã cho. Trả về 0 nếu người chơi không có nhân vật.

  • Trả về một từ điển chứa thông tin mô tả cách Player tham gia vào trải nghiệm.

  • Trả về chuột đang được sử dụng bởi khách hàng.

  • Ghi Song Song

    Trả về thời gian trễ mạng cách ly trong giây lát.

  • Trả về việc có hay không có sự xuất hiện của nhân vật của người chơi đã được tải.

  • Trả về xem người chơi có được xác minh bằng các tín hiệu cụ thể, thế giới thực hay không.

  • Kick(message : string):()

    Bắt buộc người chơi tách khỏi trò chơi, tùy chọn cung cấp một thông điệp.

  • Move(walkDirection : Vector3,relativeToCamera : boolean):()

    Gây ra nhân vật của người chơi đi theo hướng đã cho cho đến khi dừng lại, hoặc bị ngắt bởi người chơi (bằng cách sử dụng điều khiển của họ).

  • SetAccountAge(accountAge : number):()
    Bảo Mật Plugin

    Đặt tuổi tài khoản của người chơi.

  • Bảo Mật Plugin

    Xác định xem người chơi có nhìn thấy trò chuyện lọc hay không, thay vì trò chuyện bình thường.

  • Sinh Lợi

    Trả về một từ điển của bạn bè trực tuyến.

  • Sinh Lợi

    Trả về thứ hạng của người chơi trong nhóm như một số nguyên từ 0 đến 255, trong đó 0 là thành viên không và 255 là chủ nhân của nhóm.

  • Sinh Lợi

    Trả vai trò của người chơi trong nhóm dưới dạng chuỗi hoặc "Khách" nếu người chơi không thuộc nhóm.

  • Sinh Lợi

    Kiểm tra xem một người chơi có phải là bạn của người dùng với Player.UserId được cho.

  • Sinh Lợi

    Kiểm tra xem một người chơi có phải là thành viên của một nhóm với ID đã cho hay không.

  • Sinh Lợi

    Tạo một nhân vật mới cho người chơi, loại bỏ cái cũ. Cũng xóa BackpackPlayerGui của người chơi.

  • Sinh Lợi

    Tạo một avatar để nó có mọi thứ được trang bị trong đã qua HumanoidDescription .

  • RequestStreamAroundAsync(position : Vector3,timeOut : number):()
    Sinh Lợi

    Yêu cầu mà máy chủ phát trực tiếp cho người chơi xung quanh vị trí được định.

Sự Kiện

Thuộc Tính

AccountAge

Chỉ Đọc
Không Sao Chép
Đọc Song Song

Mẫu mã

Dấu hiệu tuổi tài khoản

local Players = game:GetService("Players")
local MAX_AGE_NEW_PLAYER = 7 -- một tuần
local MIN_AGE_VETERAN = 365 -- một năm
-- Chức năng này đánh dấu một phần có văn bản bằng cách sử dụng BillboardGui
local function mark(part, text)
local bbgui = Instance.new("BillboardGui")
bbgui.AlwaysOnTop = true
bbgui.StudsOffsetWorldSpace = Vector3.new(0, 2, 0)
bbgui.Size = UDim2.new(0, 200, 0, 50)
local textLabel = Instance.new("TextLabel")
textLabel.Size = UDim2.new(1, 0, 1, 0) -- Điền cha mẹ
textLabel.Text = text
textLabel.TextColor3 = Color3.new(1, 1, 1)
textLabel.TextStrokeTransparency = 0
textLabel.BackgroundTransparency = 1
textLabel.Parent = bbgui
-- Thêm vào phần
bbgui.Parent = part
bbgui.Adornee = part
end
local function onPlayerSpawned(player, character)
local head = character:WaitForChild("Head")
if player.AccountAge >= MIN_AGE_VETERAN then
mark(head, "Veteran Player")
elseif player.AccountAge <= MAX_AGE_NEW_PLAYER then
mark(head, "New Player")
else
mark(head, "Regular Player")
end
end
local function onPlayerAdded(player)
-- Lắng nghe cho người chơi này xuất hiện
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)

AutoJumpEnabled

Đọc Song Song

Mẫu mã

Chuyển đổi nhảy tự động

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local button = script.Parent
local function update()
-- Cập nhật văn bản nút
if player.AutoJumpEnabled then
button.Text = "Auto-Jump is ON"
else
button.Text = "Auto-Jump is OFF"
end
-- Phản ánh thuộc tính trong nhân vật của người chơi, nếu họ có một
if player.Character then
local human = player.Character:FindFirstChild("Humanoid")
if human then
human.AutoJumpEnabled = player.AutoJumpEnabled
end
end
end
local function onActivated()
-- Bật/tắt nhảy tự động
player.AutoJumpEnabled = not player.AutoJumpEnabled
-- Cập nhật tất cả những thứ khác
update()
end
button.Activated:Connect(onActivated)
update()

CameraMaxZoomDistance

Đọc Song Song

Mẫu mã

Setting Camera Zoom Distance

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMaxZoomDistance = 50
player.CameraMinZoomDistance = 75

CameraMinZoomDistance

Đọc Song Song

Mẫu mã

Setting Camera Zoom Distance

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMaxZoomDistance = 50
player.CameraMinZoomDistance = 75

CameraMode

Đọc Song Song

Mẫu mã

Playing in First Person

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMode = Enum.CameraMode.LockFirstPerson

CanLoadCharacterAppearance

Đọc Song Song

Mẫu mã

Disabling a Player's Appearance

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CanLoadCharacterAppearance = false

Character

Đọc Song Song

CharacterAppearanceId

Đọc Song Song

Mẫu mã

Lệnh ngụy trang

local Players = game:GetService("Players")
local disguiseCommand = "/disguise "
local function onPlayerChatted(player, message)
if message:sub(1, disguiseCommand:len()):lower() == disguiseCommand:lower() then
local input = message:sub(disguiseCommand:len() + 1)
local id = tonumber(input)
if not id then -- Số không thể phân tích, có lẽ họ đã nhập tên người dùng thay vào đó
pcall(function() -- Cuộc gọi này có thể thất bại đôi khi!
id = Players:GetUserIdFromNameAsync(input) -- Lấy ID từ tên
end)
end
if id then
-- Chỉnh sửa xuất hình nhân vật rồi hồi sinh
player.CharacterAppearanceId = id
player:LoadCharacter()
else
-- Chúng tôi không thể nhận được một ID từ nhập của họ
end
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)

DevCameraOcclusionMode

Đọc Song Song
Đọc Song Song

Mẫu mã

Setting a Player's Camera Movement Mode (Desktop)

local Players = game:GetService("Players")
local player = Players.LocalPlayer
-- Set the player's camera movement mode on computers to classic
player.DevComputerCameraMode = Enum.DevComputerCameraMovementMode.Classic

DevComputerMovementMode

Đọc Song Song

DevEnableMouseLock

Đọc Song Song

Mẫu mã

Toggling Mouse Lock Ability

local Players = game:GetService("Players")
local function toggleMouseLock(player)
player.DevEnableMouseLock = not player.DevEnableMouseLock
if player.DevEnableMouseLock then
print("Mouse lock is available")
else
print("Mouse lock is not available")
end
end
local function onPlayerChatted(player, message, _recipient)
if message == "mouselock" then
toggleMouseLock(player)
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Đọc Song Song

Mẫu mã

Setting a Player's Camera Movement Mode (Touch)

local Players = game:GetService("Players")
local player = Players.LocalPlayer
-- Set the player's camera movement mode on mobile devices to classic
player.DevTouchCameraMovementMode = Enum.DevTouchCameraMovementMode.Classic

DevTouchMovementMode

Đọc Song Song

DisplayName

Đọc Song Song

FollowUserId

Chỉ Đọc
Không Sao Chép
Đọc Song Song

Mẫu mã

Followed Alert

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local screenGui = Instance.new("ScreenGui")
screenGui.Parent = player:WaitForChild("PlayerGui")
local function onPlayerAdded(newPlayer)
if newPlayer.FollowUserId == player.UserId then
local textLabel = Instance.new("TextLabel")
textLabel.Parent = screenGui
textLabel.Text = "You were followed to this game by " .. newPlayer.Name .. "!"
task.delay(3, function()
if textLabel then
textLabel:Destroy()
end
end)
end
end
Players.PlayerAdded:Connect(onPlayerAdded)

GameplayPaused

Bảo Mật Không Thể Tiếp Cận
Đọc Song Song

HasVerifiedBadge

Đọc Song Song

HealthDisplayDistance

Đọc Song Song

Mẫu mã

Hiding Player Health and Names

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.HealthDisplayDistance = 0
player.NameDisplayDistance = 0

LocaleId

Ẩn
Chỉ Đọc
Không Sao Chép
Đọc Song Song

Mẫu mã

Checking a Player's Locale

local Players = game:GetService("Players")
local player = Players.LocalPlayer
print(player.LocaleId)

MembershipType

Chỉ Đọc
Không Sao Chép
Đọc Song Song

Mẫu mã

Check Player Membership Status

local Players = game:GetService("Players")
local player = Players.LocalPlayer
if player.MembershipType == Enum.MembershipType.Premium then
-- Take some action specifically for Premium members
end

NameDisplayDistance

Đọc Song Song

Mẫu mã

Hiding Player Health and Names

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.HealthDisplayDistance = 0
player.NameDisplayDistance = 0

Neutral

Đọc Song Song

Mẫu mã

Checking if a Player is Neutral

local Players = game:GetService("Players")
local player = Players.LocalPlayer
if player.Neutral then
print("Player is neutral!")
else
print("Player is not neutral!")
end

PartyId

Ẩn
Không Sao Chép
Bảo Mật Roblox
Đọc Song Song

Mẫu mã

Player.PartyId

local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
local partyId = player.PartyId
if partyId ~= "" then
print("Player is in a party with ID: " .. partyId)
else
warn("Player is not in a party")
end
end)

ReplicationFocus

Đọc Song Song

Mẫu mã

Đặt tập trung sao chép của một người chơi

local Players = game:GetService("Players")
local PLAYER_NAME = "polarpanda16"
local player = Players:WaitForChild(PLAYER_NAME)
local part = Instance.new("Part")
part.Parent = workspace
part.Name = "ReplicationFocusPart"
part.Anchored = true
player.ReplicationFocus = part

RespawnLocation

Đọc Song Song

Mẫu mã

Change Spawn on Touch

local Players = game:GetService("Players")
local function addSpawn(spawnLocation)
-- listen for the spawn being touched
spawnLocation.Touched:Connect(function(hit)
local character = hit:FindFirstAncestorOfClass("Model")
if character then
local player = Players:GetPlayerFromCharacter(character)
if player and player.RespawnLocation ~= spawnLocation then
local humanoid = character:FindFirstChildOfClass("Humanoid")
-- make sure the character isn't dead
if humanoid and humanoid:GetState() ~= Enum.HumanoidStateType.Dead then
print("spawn set")
player.RespawnLocation = spawnLocation
end
end
end
end)
end
local firstSpawn
-- look through the workspace for spawns
for _, descendant in pairs(workspace:GetDescendants()) do
if descendant:IsA("SpawnLocation") then
if descendant.Name == "FirstSpawn" then
firstSpawn = descendant
end
addSpawn(descendant)
end
end
local function playerAdded(player)
player.RespawnLocation = firstSpawn
end
-- listen for new players
Players.PlayerAdded:Connect(playerAdded)
-- go through existing players
for _, player in pairs(Players:GetPlayers()) do
playerAdded(player)
end

StepIdOffset

Bảo Mật Roblox
Đọc Song Song

Team

Không Sao Chép
Đọc Song Song

Mẫu mã

Playing/Spectating Teams

local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
local teamPlaying = Teams.Playing
local teamSpectators = Teams.Spectating
local playCommand = "/play"
local function play(player)
player.Team = teamPlaying
player.TeamColor = teamPlaying.TeamColor
-- Respawn the player (moves them to spawn location)
player:LoadCharacter()
end
local function onPlayerDied(player, _character)
-- When someone dies, put them on the spectator team
player.Team = teamSpectators
end
local function onPlayerSpawned(player, character)
local human = character:WaitForChild("Humanoid")
human.Died:Connect(function()
onPlayerDied(player, character)
end)
end
local function onPlayerChatted(player, message)
if message:sub(1, playCommand:len()):lower() == playCommand then
play(player)
end
end
local function onPlayerAdded(player)
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
player.Chatted:Connect(function(message, _recipient)
onPlayerChatted(player, message)
end)
end
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Join Team Command

local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
-- Command to choose a team (note the trailing space)
local joinCommand = "/jointeam "
local function findTeamByName(name)
-- First, check for the exact name of a team
if Teams:FindFirstChild(name) then
return Teams[name]
end
-- Let's check for case-insensitive partial matches, like "red" for "Red Robins"
for _, team in pairs(Teams:GetChildren()) do
if team.Name:sub(1, name:len()):lower() == name:lower() then
return team
end
end
-- If we get to this point, no team matched the one we were looking for :(
end
local function onPlayerChatted(player, message, _recipient)
-- Note: string.sub(message, ...) is the same as message:sub(...)
if message:sub(1, joinCommand:len()):lower() == joinCommand:lower() then
-- Matched "/JOINTEAM xyz" to our join command prefix "/jointeam "
local teamName = message:sub(joinCommand:len() + 1) -- Cut out the "xyz" from "/jointeam xyz"
local team = findTeamByName(teamName)
if team then
-- Set the team!
player.Team = team
player.Neutral = false
else
-- Tell the player that team could not be found :(
player.Team = nil
player.Neutral = true
end
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)

TeamColor

Đọc Song Song

Mẫu mã

Playing/Spectating Teams

local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
local teamPlaying = Teams.Playing
local teamSpectators = Teams.Spectating
local playCommand = "/play"
local function play(player)
player.Team = teamPlaying
player.TeamColor = teamPlaying.TeamColor
-- Respawn the player (moves them to spawn location)
player:LoadCharacter()
end
local function onPlayerDied(player, _character)
-- When someone dies, put them on the spectator team
player.Team = teamSpectators
end
local function onPlayerSpawned(player, character)
local human = character:WaitForChild("Humanoid")
human.Died:Connect(function()
onPlayerDied(player, character)
end)
end
local function onPlayerChatted(player, message)
if message:sub(1, playCommand:len()):lower() == playCommand then
play(player)
end
end
local function onPlayerAdded(player)
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
player.Chatted:Connect(function(message, _recipient)
onPlayerChatted(player, message)
end)
end
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)

ThirdPartyTextChatRestrictionStatus

Chỉ Đọc
Không Sao Chép
Bảo Mật Kịch Bản Roblox
Đọc Song Song

UserId

Đọc Song Song

Mẫu mã

Player.UserId

local Players = game:GetService("Players")
local function onPlayerAdded(player)
print(player.UserId)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Players:GetPlayerByUserId

local Players = game:GetService("Players")
local player = Players:GetPlayerByUserId(1)
if player then
print("Player with userId 1 is in this server! Their name is: " .. player.Name)
else
print("Player with userId 1 is not in this server!")
end
Met the Creator Badge

local BadgeService = game:GetService("BadgeService")
local Players = game:GetService("Players")
local OWNER_ID = 212423 -- can use game.CreatorId for published places
local BADGE_ID = 1
local ownerInGame = false
local function playerAdded(newPlayer)
if newPlayer.UserId == OWNER_ID then
-- if new player is the owner, set ownerInGame to true and give everyone the badge
ownerInGame = true
for _, player in pairs(Players:GetPlayers()) do
-- don't award the owner
if player ~= newPlayer then
BadgeService:AwardBadge(player.UserId, BADGE_ID)
end
end
elseif ownerInGame then
-- if the owner is in the game, award the badge
BadgeService:AwardBadge(newPlayer.UserId, BADGE_ID)
end
end
local function playerRemoving(oldPlayer)
if oldPlayer.UserId == OWNER_ID then
ownerInGame = false
end
end
Players.PlayerAdded:Connect(playerAdded)
Players.PlayerRemoving:Connect(playerRemoving)
Data Store to Leaderboard

local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local goldDataStore = DataStoreService:GetDataStore("Gold")
local STARTING_GOLD = 100
local function onPlayerAdded(player)
local playerKey = "Player_" .. player.UserId
local leaderstats = Instance.new("IntValue")
leaderstats.Name = "leaderstats"
local gold = Instance.new("IntValue")
gold.Name = "Gold"
gold.Parent = leaderstats
local success, result = pcall(function()
return goldDataStore:GetAsync(playerKey) or STARTING_GOLD
end)
if success then
gold.Value = result
else
-- Failed to retrieve data
warn(result)
end
leaderstats.Parent = player
end
Players.PlayerAdded:Connect(onPlayerAdded)

Phương Pháp

AddReplicationFocus

()

Tham Số

part: BasePart
Giá Trị Mặc Định: ""

Lợi Nhuận

()

ClearCharacterAppearance

()

Lợi Nhuận

()

Mẫu mã

How to Clear a Character's Appearance

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local function onChildRemoved(child)
print(child.ClassName, "removed from character")
end
character.ChildRemoved:Connect(onChildRemoved)
player:ClearCharacterAppearance()
--> BodyColors removed from character
--> ShirtGraphic removed from character
--> Shirt removed from character
--> Pants removed from character
--> CharacterMesh removed from character
--> Hat removed from character
--> Shirt removed from character

DistanceFromCharacter

Tham Số

point: Vector3
Giá Trị Mặc Định: ""

Lợi Nhuận

Mẫu mã

Measuring the Distance Between a Player and a Position

local Players = game:GetService("Players")
for _, player in pairs(Players:GetPlayers()) do
print(player:DistanceFromCharacter(Vector3.new(0, 0, 0)))
end

GetJoinData


Lợi Nhuận

Mẫu mã

Tracking Traffic Sources

local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local analyticsStore = DataStoreService:GetDataStore("Analytics")
local ALLOWED_SOURCES = {
"twitter",
"youtube",
"discord",
}
local function onPlayerAdded(player)
local source = player:GetJoinData().LaunchData
-- check if the provided source is valid
if source and table.find(ALLOWED_SOURCES, source) then
-- update the data store to track the source popularity
local success, result = pcall(analyticsStore.IncrementAsync, analyticsStore, source)
if success then
print(player.Name, "joined from", source, "- total:", result)
else
warn("Failed to record join source: " .. result)
end
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
Referral URL Generator

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local DIRECT_JOIN_URL = "https://www.roblox.com/games/start?placeId=%d&launchData=%s"
local textBox = script.Parent
local function generateReferralURL(player)
return DIRECT_JOIN_URL:format(game.PlaceId, player.UserId)
end
local function highlightAll()
if -- avoid recursive property updates
textBox:IsFocused() and not (textBox.SelectionStart == 1 and textBox.CursorPosition == #textBox.Text + 1)
then
textBox.SelectionStart = 1
textBox.CursorPosition = #textBox.Text + 1
end
end
textBox.Focused:Connect(highlightAll)
textBox:GetPropertyChangedSignal("SelectionStart"):Connect(highlightAll)
textBox:GetPropertyChangedSignal("CursorPosition"):Connect(highlightAll)
textBox.TextEditable = false
textBox.ClearTextOnFocus = false
textBox.Text = generateReferralURL(player)
Using a Table as Launch Data

local HttpService = game:GetService("HttpService")
local DATA_CHARACTER_LIMIT = 200
local function encodeTableAsLaunchData(data)
-- convert the table to a string
local jsonEncodedData = HttpService:JSONEncode(data)
if #jsonEncodedData <= DATA_CHARACTER_LIMIT then
-- escape potentially invalid characters, such as spaces
local urlEncodedData = HttpService:UrlEncode(jsonEncodedData)
return true, urlEncodedData
else
-- report character limit error
return false, ("Encoded table exceeds %d character limit"):format(DATA_CHARACTER_LIMIT)
end
end
local sampleData = {
joinMessage = "Hello!",
urlCreationDate = os.time(),
magicNumbers = {
534,
1337,
746733573,
},
}
local success, encodedData = encodeTableAsLaunchData(sampleData)
if success then
print(encodedData)
else
warn("failed to encode launch data: " .. encodedData)
end
Decoding JSON Launch Data

local HttpService = game:GetService("HttpService")
local Players = game:GetService("Players")
local function onPlayerAdded(player)
local launchData = player:GetJoinData().LaunchData
if launchData then
-- attempt to decode the data
local success, result = pcall(HttpService.JSONDecode, HttpService, launchData)
if success then
print(player.Name, "joined with data:", result)
else
-- this is probably due to the user messing with the URL
warn("Failed to parse launch data:" .. result)
end
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
Server TeleportData Example

local Players = game:GetService("Players")
local approvedPlaceIds = { 1 } -- insert approved PlaceIds here
local function isPlaceIdApproved(placeId)
for _, id in pairs(approvedPlaceIds) do
if id == placeId then
return true
end
end
return false
end
local function onPlayerAdded(player)
local joinData = player:GetJoinData()
-- verify this data was sent by an approved place
if isPlaceIdApproved(joinData.SourcePlaceId) then
local teleportData = joinData.TeleportData
if teleportData then
local currentLevel = teleportData.currentLevel
print(player.Name .. " is on level " .. currentLevel)
end
end
end
Players.PlayerAdded:Connect(onPlayerAdded)

GetMouse


Lợi Nhuận

Mẫu mã

How to Track Mouse Input

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
local function onButton1Down()
print("Button 1 is down")
end
mouse.Button1Down:Connect(onButton1Down)

GetNetworkPing

Ghi Song Song

Lợi Nhuận

HasAppearanceLoaded


Lợi Nhuận

Mẫu mã

Check if a Player's Appearance Has Loaded

local Players = game:GetService("Players")
local function onPlayerAdded(player)
local loaded = player:HasAppearanceLoaded()
print(loaded)
while not loaded do
loaded = player:HasAppearanceLoaded()
print(loaded)
task.wait()
end
end
Players.PlayerAdded:Connect(onPlayerAdded)

IsVerified


Lợi Nhuận

Mẫu mã

Using IsVerified

local Players = game:GetService("Players")
local function onPlayerAdded(player)
print(player:IsVerified())
end
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)

Kick

()

Tham Số

message: string
Giá Trị Mặc Định: ""

Lợi Nhuận

()

Move

()

Tham Số

walkDirection: Vector3
Giá Trị Mặc Định: ""
relativeToCamera: boolean
Giá Trị Mặc Định: false

Lợi Nhuận

()

Mẫu mã

Moving the Player relative to their Camera

local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
-- Wait for the player's character and humanoid, which must exist before calling :Move()
local character = localPlayer.Character or localPlayer.CharacterAdded:Wait()
character:WaitForChild("Humanoid")
-- The player will move until they are 50 studs away from the camera's position at the time of running
localPlayer:Move(Vector3.new(0, 0, -50), true)

RemoveReplicationFocus

()

Tham Số

part: BasePart
Giá Trị Mặc Định: ""

Lợi Nhuận

()

SetAccountAge

()
Bảo Mật Plugin

Tham Số

accountAge: number
Giá Trị Mặc Định: ""

Lợi Nhuận

()

Mẫu mã

Setting the Player's Account Age

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player:SetAccountAge(100)
Dấu hiệu tuổi tài khoản

local Players = game:GetService("Players")
local MAX_AGE_NEW_PLAYER = 7 -- một tuần
local MIN_AGE_VETERAN = 365 -- một năm
-- Chức năng này đánh dấu một phần có văn bản bằng cách sử dụng BillboardGui
local function mark(part, text)
local bbgui = Instance.new("BillboardGui")
bbgui.AlwaysOnTop = true
bbgui.StudsOffsetWorldSpace = Vector3.new(0, 2, 0)
bbgui.Size = UDim2.new(0, 200, 0, 50)
local textLabel = Instance.new("TextLabel")
textLabel.Size = UDim2.new(1, 0, 1, 0) -- Điền cha mẹ
textLabel.Text = text
textLabel.TextColor3 = Color3.new(1, 1, 1)
textLabel.TextStrokeTransparency = 0
textLabel.BackgroundTransparency = 1
textLabel.Parent = bbgui
-- Thêm vào phần
bbgui.Parent = part
bbgui.Adornee = part
end
local function onPlayerSpawned(player, character)
local head = character:WaitForChild("Head")
if player.AccountAge >= MIN_AGE_VETERAN then
mark(head, "Veteran Player")
elseif player.AccountAge <= MAX_AGE_NEW_PLAYER then
mark(head, "New Player")
else
mark(head, "Regular Player")
end
end
local function onPlayerAdded(player)
-- Lắng nghe cho người chơi này xuất hiện
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)

SetSuperSafeChat

()
Bảo Mật Plugin

Tham Số

value: boolean
Giá Trị Mặc Định: ""

Lợi Nhuận

()

GetFriendsOnline

Sinh Lợi

Tham Số

maxFriends: number
Giá Trị Mặc Định: 200

Lợi Nhuận

Mẫu mã

Nhận danh sách bạn bè trực tuyến

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local success, result = pcall(player.GetFriendsOnline, player, 10)
if success then
for _, friend in pairs(result) do
print(friend.UserName)
end
else
warn("Failed to get online players: " .. result)
end

GetRankInGroup

Sinh Lợi

Tham Số

groupId: number
Giá Trị Mặc Định: ""

Lợi Nhuận

Mẫu mã

How to Check a Player's Rank in a Group

local Players = game:GetService("Players")
local function onPlayerAdded(player)
if player:GetRankInGroup(2) == 255 then
print("Player is the owner of the group, 'LOL'!")
else
print("Player is NOT the owner of the group, 'LOL'!")
end
end
Players.PlayerAdded:Connect(onPlayerAdded)

GetRoleInGroup

Sinh Lợi

Tham Số

groupId: number
Giá Trị Mặc Định: ""

Lợi Nhuận

Mẫu mã

How to Check a Player's Role in a Group

local Players = game:GetService("Players")
local function onPlayerAdded(player)
print("Player is ranked as '", player:GetRoleInGroup(2), "' in group, 'LOL'!")
end
Players.PlayerAdded:Connect(onPlayerAdded)

IsFriendsWith

Sinh Lợi

Tham Số

userId: number
Giá Trị Mặc Định: ""

Lợi Nhuận

Mẫu mã

How to Check if a Player is a Connection

local Players = game:GetService("Players")
local function onPlayerAdded(player)
if player:IsFriendsWith(146569) then
print(player.Name .. " is connections with gordonrox24!")
end
end
Players.PlayerAdded:Connect(onPlayerAdded)

IsInGroup

Sinh Lợi

Tham Số

groupId: number
Giá Trị Mặc Định: ""

Lợi Nhuận

Mẫu mã

How to Check if a Player is in a Group

local Players = game:GetService("Players")
local function onPlayerAdded(player)
if player:IsInGroup(7) then
print("Player is in the Roblox Fan club!")
end
end
Players.PlayerAdded:Connect(onPlayerAdded)

LoadCharacter

()
Sinh Lợi

Lợi Nhuận

()

Mẫu mã

Turn Off Auto-Loading and Simulate Character Respawn

local Players = game:GetService("Players")
local RESPAWN_DELAY = 5
Players.CharacterAutoLoads = false
local function onPlayerAdded(player)
local function onCharacterAdded(character)
local humanoid = character:WaitForChild("Humanoid")
local function onDied()
task.wait(RESPAWN_DELAY)
player:LoadCharacter()
end
humanoid.Died:Connect(onDied)
end
player.CharacterAdded:Connect(onCharacterAdded)
player:LoadCharacter()
end
Players.PlayerAdded:Connect(onPlayerAdded)

LoadCharacterWithHumanoidDescription

()
Sinh Lợi

Tham Số

humanoidDescription: HumanoidDescription
Giá Trị Mặc Định: ""

Lợi Nhuận

()

Mẫu mã

Spawn Characters With HumanoidDescription

local Players = game:GetService("Players")
Players.CharacterAutoLoads = false
local function onPlayerAdded(player)
local humanoidDescription = Instance.new("HumanoidDescription")
humanoidDescription.HatAccessory = "2551510151,2535600138"
humanoidDescription.BodyTypeScale = 0.1
humanoidDescription.ClimbAnimation = 619521311
humanoidDescription.Face = 86487700
humanoidDescription.GraphicTShirt = 1711661
humanoidDescription.HeadColor = Color3.new(0, 1, 0)
player:LoadCharacterWithHumanoidDescription(humanoidDescription)
end
Players.PlayerAdded:Connect(onPlayerAdded)

RequestStreamAroundAsync

()
Sinh Lợi

Tham Số

position: Vector3
Giá Trị Mặc Định: ""
timeOut: number
Giá Trị Mặc Định: 0

Lợi Nhuận

()

Sự Kiện

CharacterAdded

Tham Số

character: Model

Mẫu mã

Detecting Player Spawns and Despawns

local Players = game:GetService("Players")
local function onCharacterAdded(character)
print(character.Name .. " has spawned")
end
local function onCharacterRemoving(character)
print(character.Name .. " is despawning")
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(onCharacterAdded)
player.CharacterRemoving:Connect(onCharacterRemoving)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Respawn at Despawn Location

local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
-- This table maps "Player" objects to Vector3
local respawnLocations = {}
local function onCharacterAdded(character)
local player = Players:GetPlayerFromCharacter(character)
-- Check if we saved a respawn location for this player
if respawnLocations[player] then
-- Teleport the player there when their HumanoidRootPart is available
local hrp = character:WaitForChild("HumanoidRootPart")
-- Wait a brief moment before teleporting, as Roblox will teleport the
-- player to their designated SpawnLocation (which we will override)
RunService.Stepped:wait()
hrp.CFrame = CFrame.new(respawnLocations[player] + Vector3.new(0, 3.5, 0))
end
end
local function onCharacterRemoving(character)
-- Get the player and their HumanoidRootPart and save their death location
local player = Players:GetPlayerFromCharacter(character)
local hrp = character:FindFirstChild("HumanoidRootPart")
if hrp then
respawnLocations[player] = hrp.Position
end
end
local function onPlayerAdded(player)
-- Listen for spawns/despawns
player.CharacterAdded:Connect(onCharacterAdded)
player.CharacterRemoving:Connect(onCharacterRemoving)
end
local function onPlayerRemoved(player)
-- Forget the respawn location of any player who is leaving; this prevents
-- a memory leak if potentially many players visit
respawnLocations[player] = nil
end
-- Note that we're NOT using PlayerRemoving here, since CharacterRemoving fires
-- AFTER PlayerRemoving, we don't want to forget the respawn location then instantly
-- save another right after
Players.PlayerAdded:Connect(onPlayerAdded)
Players.ChildRemoved:Connect(onPlayerRemoved)
Loại bỏ phụ kiện

local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local function destroyAccessory(object)
if object:IsA("Hat") or object:IsA("Accessory") then
object:Destroy()
end
end
local function onCharacterAdded(character)
-- Chờ một lúc ngắn trước khi gỡ bỏ phụ kiện để tránh
-- Cảnh báo "Something unexpectedly set ___ parent to NULL"
RunService.Stepped:Wait()
-- Kiểm tra các phụ kiện hiện có trong nhân vật của người chơi
for _, child in pairs(character:GetChildren()) do
destroyAccessory(child)
end
-- Nón có thể được thêm vào nhân vật một lúc sau
-- Nhân vật được thêm vào, vì vậy chúng tôi lắng nghe những người sử dụng ChildAdded
character.ChildAdded:Connect(destroyAccessory)
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(onCharacterAdded)
end
Players.PlayerAdded:Connect(onPlayerAdded)

CharacterAppearanceLoaded

Tham Số

character: Model

Mẫu mã

Loại bỏ phụ kiện sau khi tải

local Players = game:GetService("Players")
local function onPlayerAddedAsync(player)
local connection = player.CharacterAppearanceLoaded:Connect(function(character)
-- Tất cả các phụ kiện đã được tải tại thời điểm này
local humanoid = character:FindFirstChildOfClass("Humanoid")
local numAccessories = #humanoid:GetAccessories()
print(("Destroying %d accessories for %s"):format(numAccessories, player.Name))
humanoid:RemoveAccessories()
end)
-- Hãy chắc chắn rằng chúng ta cắt kết nối với người chơi sau khi họ rời đi
-- để cho phép người chơi nhận được rác được thu thập
player.AncestryChanged:Wait()
connection:Disconnect()
end
for _, player in Players:GetPlayers() do
task.spawn(onPlayerAddedAsync, player)
end
Players.PlayerAdded:Connect(onPlayerAddedAsync)

CharacterRemoving

Tham Số

character: Model

Mẫu mã

Player.CharacterRemoving

game.Players.PlayerAdded:Connect(function(player)
player.CharacterRemoving:Connect(function(character)
print(character.Name .. " has died.")
end)
end)

Chatted

Tham Số

message: string
recipient: Player

Mẫu mã

Player.Chatted

local Players = game:GetService("Players")
local function onPlayerAdded(player)
local function onChatted(message)
-- do stuff with message and player
print(message)
end
player.Chatted:Connect(onChatted)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Playing/Spectating Teams

local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
local teamPlaying = Teams.Playing
local teamSpectators = Teams.Spectating
local playCommand = "/play"
local function play(player)
player.Team = teamPlaying
player.TeamColor = teamPlaying.TeamColor
-- Respawn the player (moves them to spawn location)
player:LoadCharacter()
end
local function onPlayerDied(player, _character)
-- When someone dies, put them on the spectator team
player.Team = teamSpectators
end
local function onPlayerSpawned(player, character)
local human = character:WaitForChild("Humanoid")
human.Died:Connect(function()
onPlayerDied(player, character)
end)
end
local function onPlayerChatted(player, message)
if message:sub(1, playCommand:len()):lower() == playCommand then
play(player)
end
end
local function onPlayerAdded(player)
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
player.Chatted:Connect(function(message, _recipient)
onPlayerChatted(player, message)
end)
end
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Join Team Command

local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
-- Command to choose a team (note the trailing space)
local joinCommand = "/jointeam "
local function findTeamByName(name)
-- First, check for the exact name of a team
if Teams:FindFirstChild(name) then
return Teams[name]
end
-- Let's check for case-insensitive partial matches, like "red" for "Red Robins"
for _, team in pairs(Teams:GetChildren()) do
if team.Name:sub(1, name:len()):lower() == name:lower() then
return team
end
end
-- If we get to this point, no team matched the one we were looking for :(
end
local function onPlayerChatted(player, message, _recipient)
-- Note: string.sub(message, ...) is the same as message:sub(...)
if message:sub(1, joinCommand:len()):lower() == joinCommand:lower() then
-- Matched "/JOINTEAM xyz" to our join command prefix "/jointeam "
local teamName = message:sub(joinCommand:len() + 1) -- Cut out the "xyz" from "/jointeam xyz"
local team = findTeamByName(teamName)
if team then
-- Set the team!
player.Team = team
player.Neutral = false
else
-- Tell the player that team could not be found :(
player.Team = nil
player.Neutral = true
end
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)

Idled

Tham Số

time: number

Mẫu mã

Player.Idled

local Players = game:GetService("Players")
local function onIdled(idleTime)
print(`Player has been idle for {idleTime} seconds`)
if idleTime > 900 then
-- warn player that they've been idle for 15 minutes
-- and will be disconnected in another 5
end
end
Players.LocalPlayer.Idled:Connect(onIdled)

OnTeleport

Tham Số

teleportState: Enum.TeleportState
placeId: number
spawnName: string

Mẫu mã

Player.OnTeleport

local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
local playerOnTeleport = player
player.OnTeleport:Connect(function(teleportState, _placeId, _spawnName)
if teleportState == Enum.TeleportState.Started then
print("Teleport started (" .. playerOnTeleport.Name .. ")")
elseif teleportState == Enum.TeleportState.WaitingForServer then
print("Teleport waiting for server (" .. playerOnTeleport.Name .. ")")
elseif teleportState == Enum.TeleportState.InProgress then
print("Teleport in progress (" .. playerOnTeleport.Name .. ")")
elseif teleportState == Enum.TeleportState.Failed then
print("Teleport failed! (" .. playerOnTeleport.Name .. ")")
end
end)
end)