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 tài khoảndù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 tài khoảndù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ã

This code sample demonstrates the creation of leaderboard stat values in Roblox's default player list UI. It creates a "Score" leaderstat that starts at 0.

Leaderstats

local Players = game:GetService("Players")
local function onPlayerAdded(player)
-- Create a container for leaderstats
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
-- Create one leaderstat value
local vScore = Instance.new("IntValue")
vScore.Name = "Score"
vScore.Value = 0
vScore.Parent = leaderstats
-- Add to player (displaying it)
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ự ngoại hìnhmặ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 chơidù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ả đánh máythà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
  • Đọc Song Song

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

  • Nếu được cài đặ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 tin nhắn.

  • 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

Tuổi tài khoản là một Player tính năng mô tả thời gian tài khoản của một người chơi đã được đăng ký trong các ngày.Nó được đặt bằng cách sử dụng chức năng Player:SetAccountAge(), không thể truy cập bởi các kịch bản.

Tính năng này hữu ích để hiển thị tạm thời nội dung mới của người chơi Roblox như hướng dẫn.

Mẫu mã

This code sample adds a mark to players showing about how old their account is. The mark uses a player's account age to determine if they are a New Player, Veteran Player or Regular Player.

Account Age Mark

local Players = game:GetService("Players")
local MAX_AGE_NEW_PLAYER = 7 -- one week
local MIN_AGE_VETERAN = 365 -- one year
-- This function marks a part with text using a 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) -- Fill parent
textLabel.Text = text
textLabel.TextColor3 = Color3.new(1, 1, 1)
textLabel.TextStrokeTransparency = 0
textLabel.BackgroundTransparency = 1
textLabel.Parent = bbgui
-- Add to part
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)
-- Listen for this player spawning
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

Thuộc tính AutoJumpEnabled xác định xem Player.Character của Player sử dụng thiết bị di động sẽ tự động nhảy khi chúng va chạm với một chướng ngại vật.Điều này có thể làm cho các cấp trở nên dễ di chuyển hơn trên thiết bị di động.

Khi người chơi tham gia trò chơi, giá trị StarterPlayer.AutoJumpEnabled xác định trạng thái ban đầu của thuộc tính này.Sau đó, thuộc tính này xác định giá trị của thuộc tính Humanoid.AutoJumpEnabled của Player.Character trong quá trình spawn.Nói cách khác, bạn có thể đặt hành vi nhảy tự động trên mỗi nhân vật, mỗi người chơi và mỗi trò chơi dựa trên ba thuộc tính này.

Mẫu mã

This code sample is meant for a TextButton. It allows the player to toggle the auto-jumping behavior while on a mobile device.

Auto-Jump Toggle

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local button = script.Parent
local function update()
-- Update button text
if player.AutoJumpEnabled then
button.Text = "Auto-Jump is ON"
else
button.Text = "Auto-Jump is OFF"
end
-- Reflect the property in the player's character, if they have one
if player.Character then
local human = player.Character:FindFirstChild("Humanoid")
if human then
human.AutoJumpEnabled = player.AutoJumpEnabled
end
end
end
local function onActivated()
-- Toggle auto-jump
player.AutoJumpEnabled = not player.AutoJumpEnabled
-- Update everything else
update()
end
button.Activated:Connect(onActivated)
update()

CameraMaxZoomDistance

Đọc Song Song

Thuộc tính CameraMaxZoomDistance Player đặt khoảng cách tối đa trong milimet mà camera có thể từ nhân vật với các máy ảnh mặc định.

Nói cách khác, nó kiểm soát khoảng cách tối đa mà camera của người chơi được phép phóng to.

Giá trị mặc định của thuộc tính này được đặt bởi StarterPlayer.CameraMaxZoomDistance .Nếu giá trị này được đặt thành giá trị thấp hơn Player.CameraMinZoomDistance , nó sẽ được tăng lên thành CameraMinZoomDistance.

Mẫu mã

The example demonstrates how to set a player's camera minimum and maximum zoom distance.

In this example, we set the Player.CameraMinZoomDistance and Player.CameraMaxZoomDistance to set the min and max distance in studs a player's camera can be from their character.

Note that since the example attempts to set the CameraMinZoomDistance to be greater than the CameraMaxZoomDistance, the CameraMinZoomDistance value will be decreased and set to the value of the max zoom distance.

To change the default min and max zoom distance values for a player when they first enter the game, you can change the StarterClass.Player.CameraMinZoomDistance and StarterClass.Player.CameraMaxZoomDistance properties.

Setting Camera Zoom Distance

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

CameraMinZoomDistance

Đọc Song Song

Thuộc tính CameraMinZoonDistance Player đặt khoảng cách tối thiểu trong milimet mà camera có thể từ nhân vật với các máy ảnh mặc định.

Nói cách khác, nó kiểm soát khoảng cách tối thiểu mà máy ảnh của người chơi được phép phóng to.

Giá trị mặc định của thuộc tính này được đặt bởi StarterPlayer.CameraMinZoomDistance .Nếu giá trị này được đặt thành giá trị cao hơn Player.CameraMaxZoomDistance nó sẽ bị giảm xuống thành CameraMaxZoomDistance.

Mẫu mã

The example demonstrates how to set a player's camera minimum and maximum zoom distance.

In this example, we set the Player.CameraMinZoomDistance and Player.CameraMaxZoomDistance to set the min and max distance in studs a player's camera can be from their character.

Note that since the example attempts to set the CameraMinZoomDistance to be greater than the CameraMaxZoomDistance, the CameraMinZoomDistance value will be decreased and set to the value of the max zoom distance.

To change the default min and max zoom distance values for a player when they first enter the game, you can change the StarterClass.Player.CameraMinZoomDistance and StarterClass.Player.CameraMaxZoomDistance properties.

Setting Camera Zoom Distance

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

CameraMode

Đọc Song Song

Thuộc tính CameraMode đặt chế độ camera của người chơi, mặc định là người thứ ba.

Người thứ ba

Trong chế độ người thứ ba mặc định ( Enum.CameraMode.Classic ), nhân vật có thể được nhìn thấy trong máy ảnh. Trong khi ở chế độ này, hành vi mặc định là:

  • Người chơi có thể nhấp chuột phải và kéo (chuột), nhấn và kéo (di động), sử dụng cần gạt thứ cấp (gamepad), hoặc nhấn mũi tên trái/phải (bàn phím) để xoay máy ảnh xung quanh nhân vật của họ.
  • Khi một người chơi di chuyển nhân vật của họ, nó đối mặt với hướng di chuyển tương ứng.
  • Người chơi có thể phóng to và nhỏ tự do, ngay cả đối với người đầu tiên trong toàn bộ phóng to.

Người đầu tiên

Trong chế độ người thứ nhất ( Enum.CameraMode.LockFirstPerson ), máy ảnh của người chơi được phóng to suốt cả đườngTrừ khi có một GUI hiển thị với thuộc tính GuiButton.Modal được đặt thành true , di chuyển chuột, kéo trên di động hoặc sử dụng cần gạt thứ cấp trên gamepad sẽ xoay máy ảnh xung quanh nhân vật.

Mẫu mã

This example demonstrates how to change the character's CameraMode to first person using the LockFirstPerson value of the Enum.CameraMode enum.

Playing in First Person

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

CanLoadCharacterAppearance

Đọc Song Song

Thuộc tính CanLoadCharacterAppearance Player 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.Giá trị mặc định của thuộc tính này được đặt bởi StarterPlayer.LoadPlayerAppearance .

Nếu đúng, nhân vật sẽ tải trang phục của người chơi tương ứng với trang phục của người chơi Player.CharacterAppearanceId .

Nếu sai , người chơi sẽ xuất hiện với một cái nhìn mặc định - một mô hình nhân vật màu xám không có mũ, áo sơ mi, quần, v.v.

Cố gắng thiết lập thuộc tính sau khi nhân vật được tạo ra sẽ không thay đổi nhân vật, bạn phải gọi Player:LoadCharacter() để tải trang ngoại hìnhmới.

Mẫu mã

This example demonstrates how to disable loading a player's character appearance. Instead, the player loads as a grey model without any hats, shirts, pants, etc.

This is useful for games using custom clothing and accessories.

Note that if the character has already spawned, this change will not take affect until the player respawns or the Player:LoadCharacter() function is called.

Disabling a Player's Appearance

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

Character

Đọc Song Song

Thuộc tính Nhân vật bao gồm một tham chiếu đến một Model 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 cần thiết để mô phỏng avatar của người chơi trong trải nghiệm.Mô hình được gán cho Workspace nhưng nó có thể được di chuyển.Nó được tải tự động khi Players.CharacterAutoLoadstrue và nó có thể được tải thủ công bằng cách sử dụng Player:LoadCharacter() .

Lúc đầu, thuộc tính này là nil và nó được đặt khi nhân vật của người chơi xuất hiện lần đầu tiên.Sử dụng sự kiện Player.CharacterAdded để phát hiện khi nào nhân vật của người chơi tải đúng cách, và sự kiện Player.CharacterRemoving để phát hiện khi nào nhân vật sắp biến mất.Tránh sử dụng Object:GetPropertyChangedSignal() trên tính năng này.

Lưu ý rằng những thứ được sao chép từ > hoặc > vào người chơi's > hoặc > lần lượt là thường được chạy trước khi mô hình nhân vật cũ được thay thế, vì vậy > có thể đề cập đến mô hình cũ có đặc tính > .Do đó, trong một LocalScript dưới StarterGui hoặc StarterPack , tốt nhất là phải chắc chắn rằng cha của Nhân vật không phải là nil trước khi sử dụng nó, ví dụ:


local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character
if not character or character.Parent == nil then
character = player.CharacterAdded:Wait()
end

CharacterAppearanceId

Đọc Song Song

Thuộc tính này xác định ID người dùng của tài khoản mà ngoại hình nhân vật được sử dụng cho một người chơi character .Mặc định, thuộc tính này là Player.UserId, sử dụng avatar của người chơi như họ đã tạo nó trên trang web Roblox.

Thay đổi thuộc tính này thành ID người dùng của tài khoản khác sẽ khiến người chơi xuất hiện với trang phục của tài khoản đó (mũ, áo, quần, v.v.).

Trò chơi cũng có thể chuyển đổi xem liệu nhân vật của người chơi có xuất hiện trong trò chơi hay không bằng cách thay đổi thuộc tính StarterPlayer.LoadCharacterAppearance.

Mẫu mã

This code sample allows players to chat "/disguise xyz", where xyz is a user ID or username, and they will respawn appearing like that account's avatar. Try typing "/disguise 261" or "/disguise Shedletsky"!

Disguise Command

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 -- Number failed to parse, maybe they typed a username instead
pcall(function() -- This call can fail sometimes!
id = Players:GetUserIdFromNameAsync(input) -- Fetch ID from name
end)
end
if id then
-- Set character appearance then respawn
player.CharacterAppearanceId = id
player:LoadCharacter()
else
-- We couldn't get an ID from their input
end
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)

DevCameraOcclusionMode

Đọc Song Song

Xác định cách các kịch bản camera mặc định xử lý các đối tượng giữa máy ảnh và chủ đề máy ảnh.Được đặt bởi StarterPlayer.DevCameraOcclusionMode và không thể thay đổi cho mỗi người chơi.

Giá trị mặc định là Zoom (0). Xem Enum.DevCameraOcclusionMode để có danh sách các chế độ có sẵn.

Đọc Song Song

Thuộc tính DevComputerCameraMode xác định cách mà một người chơi di chuyển máy ảnh của họ khi sử dụng một thiết bị có chuột và bàn phím.Xem Enum.DevComputerCameraMovementMode để có một sự mô tả về mỗi chế độ điều khiển máy ảnh có sẵn.Thuộc tính này không thể được đặt bằng cách sử dụng LocalScript (nó phải được đặt trên máy chủ bằng cách sử dụng Script ).

Giá trị mặc định của thuộc tính này được xác định bởi StarterPlayer.DevComputerCameraMovementMode .

Từ "Máy tính" trong tên thuộc tính này đề cập đến các thiết bị không TouchEnabled , không GamepadEnabled .

Khi được đặt thành Tùy chọn người dùng , một người chơi có thể chọn bất kỳ chế độ điều khiển nào (ngoại trừ Có thể thực hiện ) trong cài đặt trò chơi Roblox.Nói phổ quát, đây là một ý tưởng tốt để cho phép người chơi chọn chế độ điều khiển của họ để tối đa hóa khả năng truy cập.

Bạn có thể tạo một sơ đồ điều khiển tùy chỉnh bằng cách đặt thuộc tính này thành Có thể thực hiện .

Thuộc tính này không ảnh hưởng đến người chơi sử dụng thiết bị có chức năng chạm. Xem Player.DevTouchCameraMode thay vào đó.

Mẫu mã

The example demonstrates how to set a player's camera movement mode for players on a computer.

In this example, we set the camera movement mode to Classic via the Enum.DevComputerCameraMovementMode enum. This means that the camera of players on touch enabled devices will track the player but will not automatically rotate if the player walks left or right.

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

Tính năng DevComputerMovementMode xác định cách mà một người chơi di chuyển nhân vật của họ khi sử dụng một thiết bị với chuột và bàn phím.Xem Enum.DevComputerMovementMode để có một sự mô tả về mỗi chế độ điều khiển di chuyển có sẵn.Thuộc tính này không thể được đặt bằng cách sử dụng LocalScript (nó phải được đặt trên máy chủ bằng cách sử dụng Script ).

Giá trị mặc định của thuộc tính này được xác định bởi StarterPlayer.DevComputerMovementMode .

Từ "Máy tính" trong tên thuộc tính này đề cập đến các thiết bị không TouchEnabled .

Khi được đặt thành Tùy chọn người dùng , một người chơi có thể chọn bất kỳ chế độ điều khiển nào (ngoại trừ Có thể thực hiện ) trong cài đặt trò chơi Roblox.Nói phổ quát, đây là một ý tưởng tốt để cho phép người chơi chọn chế độ điều khiển của họ để tối đa hóa khả năng truy cập.

Bạn có thể tạo một sơ đồ điều khiển tùy chỉnh bằng cách đặt thuộc tính này thành Có thể thực hiện .

Thuộc tính này không ảnh hưởng đến người chơi sử dụng thiết bị có khả năng chạm. Xem Player.DevTouchMovementMode.

Mẫu mã

Demonstrates how to set the movement mode for players on computers using the Player.DevComputerMovementMode property.

Setting a Player's Movement Mode (Desktop)

local Players = game:GetService("Players")
local function onPlayerAdded(player: Player)
-- Set the player's movement mode on desktop devices to click-to-move
-- Once set, the player can right click in the game world and the character will move there.
player.DevComputerMovementMode = Enum.DevComputerMovementMode.ClickToMove
end
Players.PlayerAdded:Connect(onPlayerAdded)

DevEnableMouseLock

Đọc Song Song

Thuộc tính này xác định xem người chơi có thể chuyển đổi Mouse khóa bằng cách nhấn Shift không.Một người chơi có thể vô hiệu hóa công tắc chặn chuột trong cài đặt trò chơi của Roblox.Mặc định, thuộc tính này được đặt thành giá trị của StarterPlayer.EnableMouseLockOption .Điều này có thể được thiết lập bên máy chủ trong lúc chạy bằng cách sử dụng một Script .Nó không thể được đặt bên khách.

Khi bật khóa chuột, con trỏ của người chơi được khóa vào trung tâm của màn hình.Di chuyển chuột sẽ quay quanh máy ảnh xung quanh người chơi character , và nhân vật sẽ đối mặt với cùng một hướng như camera .Nó cũng bù trừ góc nhìn camera chỉ hơn vai phải của nhân vật của người chơi.

Lưu ý rằng các API liên quan đến shift-lock đang trong quá trình bị lược bỏ, vì vậy nó được khuyến khích sử dụng UserInputService.MouseBehavior thay vì khóa chuột.

Mẫu mã

This code sample demonstrates how to toggle whether mouse lock is available to a player using a chat command. When a player types "mouselock", their ability to toggle mouse lock is toggled. Note that this does not toggle the actual state of mouse lock; rather, it changes whether a player is able to toggle it themselves.

This code can be run by pasting it into a Script within ServerScriptService.

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

Thuộc tính DevTouchCameraMode xác định cách mà một người chơi di chuyển máy ảnh của họ khi sử dụng một thiết bị TouchEnabled.Xem Enum.DevTouchCameraMovementMode để có một sự mô tả về mỗi chế độ điều khiển máy ảnh có sẵn.Thuộc tính này không thể được đặt bằng cách sử dụng LocalScript (nó phải được đặt trên máy chủ bằng cách sử dụng Script ).

Giá trị mặc định của thuộc tính này được xác định bởi StarterPlayer.DevTouchCameraMovementMode .

Khi được đặt thành Tùy chọn người dùng , một người chơi có thể chọn bất kỳ chế độ điều khiển nào (ngoại trừ Có thể thực hiện ) trong cài đặt trò chơi Roblox.Nói phổ quát, đây là một ý tưởng tốt để cho phép người chơi chọn chế độ điều khiển của họ để tối đa hóa khả năng truy cập.

Bạn có thể tạo một sơ đồ điều khiển tùy chỉnh bằng cách đặt thuộc tính này thành Có thể thực hiện .

Thuộc tính này không ảnh hưởng đến người chơi không sử dụng thiết bị có khả năng chạm. Xem Player.DevComputerCameraMovementMode thay vào đó.

Mẫu mã

The example demonstrates how to set a player's camera movement mode.

In this example, we set the camera movement mode to Classic via the Enum.DevTouchCameraMovementMode enum. This means that the camera of players on touch enabled devices will track the player but will not automatically rotate if the player walks left or right.

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

Thuộc tính DevTouchMovementMode xác định cách mà một người chơi di chuyển nhân vật của họ khi sử dụng một thiết bị TouchEnabled.Xem Enum.DevTouchMovementMode để có một sự mô tả về mỗi chế độ điều khiển di chuyển có sẵn.Thuộc tính này không thể được đặt bằng cách sử dụng LocalScript (nó phải được đặt trên máy chủ bằng cách sử dụng Script ).

Giá trị mặc định của thuộc tính này được xác định bởi StarterPlayer.DevTouchMovementMode .

Khi được đặt thành Tùy chọn người dùng , một người chơi có thể chọn bất kỳ chế độ điều khiển nào (ngoại trừ Có thể thực hiện ) trong cài đặt trò chơi Roblox.Nói phổ quát, đây là một ý tưởng tốt để cho phép người chơi chọn chế độ điều khiển của họ để tối đa hóa khả năng truy cập.

Bạn có thể tạo một sơ đồ điều khiển tùy chỉnh bằng cách đặt thuộc tính này thành Có thể thực hiện .

Thuộc tính này không ảnh hưởng đến người chơi không sử dụng thiết bị có khả năng chạm. Xem Player.DevComputerMovementMode thay vào đó.

Mẫu mã

The example demonstrates how to set the movement mode for players on touch enabled devices.

In this example, we set the movement mode to Thumbstick via the Enum.DevTouchMovementMode enum. This means that players on touch enabled devices are able to move via a virtual thumbstick on their screen.

Setting a Player's Movement Mode (Touch)

local Players = game:GetService("Players")
game.Players.PlayerAdded:Connect(function(player)
-- Set the player's movement mode on mobile devices to a dynamic thumbstick
player.DevTouchMovementMode = Enum.DevTouchMovementMode.DynamicThumbstick
end)

DisplayName

Đọc Song Song

Các thuộc tính DisplayName là một thuộc tính Player chứa tên hiển thị của người dùng đã xác thực liên quan đến đối tượng Player.Không giống như tên người dùng, tên hiển thị là những tên không duy nhất mà một người chơi hiển thị cho người khác.Nếu người dùng Roblox chưa chọn một, thuộc tính sẽ đọc giống như thuộc tính Name.

Ghi chú:

  • Vì các tên hiển thị không duy nhất, có thể hai người chơi trong một instance có cùng tên.Nếu bạn cần một nhận dạng duy nhất toàn cầu cho một người chơi, hãy sử dụng Player.UserId (đó là tĩnh) hoặc Player.Name (đó là Tên người dùng hiện tại) thay thế.
  • Các nhân vật được tạo với Player.LoadCharacter hoặc bởi động cơ Roblox sẽ có thuộc tính Humanoid.DisplayName được gán cho thuộc tính Player.DisplayName.
  • Tên hiển thị có thể có các ký tự Unicode trong chuỗi. Xem UTF-8 để biết thêm thông tin về cách làm việc với chuỗi có các ký tự Unicode.

FollowUserId

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

FollowUserId là một Player tính năng chứa Player.UserId của người dùng mà một người chơi theo dõi vào trò chơi.Nếu người chơi không theo bất kỳ ai vào trò chơi, thuộc tính này sẽ là 0.Tính năng này hữu ích để cảnh báo người chơi đã bị theo dõi bởi người chơi khác vào trò chơi.

Bạn có thể nhận được tên của người chơi theo dõi bằng ID người dùng này và chức năng Players:GetNameFromUserIdAsync().

Mẫu mã

This code sample alerts players if a new player follows the local player into the game. Place this in a LocalScript in StarterPlayerScripts.

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

Thuộc tính GameplayPaused cho thấy nếu người chơi hiện đang ở trong trạng thái tạm dừng ở một nơi có StreamingEnabled được kích hoạt.Nó được đặt trên máy khách nhưng sao chép lên máy chủ.Để xác định tình trạng tạm dừng, bạn có thể sử dụng thuộc tính này.

Xem thêm:

HasVerifiedBadge

Đọc Song Song

Thuộc tính HasVerifiedBadge Player cho thấy nếu người chơi có một Huy hiệu đã xác minh.

HealthDisplayDistance

Đọc Song Song

Thuộc tính HealthDisplayDistance đặt khoảng cách bằng đinh tán ở đó mà người chơi này sẽ nhìn thấy các thanh sức khỏe khác.Nếu đặt thành 0, các thanh sức khỏe sẽ không được hiển thị.Thuộc tính này được đặt thành StarterPlayer.HealthDisplayDistance mặc định.

Nếu thanh sức khỏe của một Humanoid hiển thị, bạn có thể đặt loại hiển thị bằng cách sử dụng Humanoid.DisplayDistanceType .

Mẫu mã

This example demonstrates how to hide other Humanoid's (Player and NPC) health bars and names.

This is done by setting the player's Player.HealthDisplayDistance and Player.NameDisplayDistance properties to 0.

If you would like to display health bars and names, you set the properties to a value greater than 0. For instance, setting the properties to 100 means that the player will see other player's health and names up to 100 studs away.

To modify the default values for players, you can change the values of the StarterClass.Player.HealthDisplayDistance and StarterClass.Player.NameDisplayDistance properties.

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

Thuộc tính LocaleId Player 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ọ.Nó giữ một chuỗi với mã hai chữ cái (ví dụ, "en-us") cho địa phương.

Nó có thể được sử dụng để xác định cơ sở dân số địa lý của cơ sở người chơi trò chơi của bạn, và cũng là khu vực sẽ được sử dụng cho bản dịch tự động của nội dung trong kinh nghiệm (xem GuiBase2d.AutoLocalize ).Tính năng này cho phép truy cập vào máy chủ của người chơi từ máy chủ.

Xem thêm LocalizationService.RobloxLocaleId , ID địa phương được sử dụng để dịch chứa nội dung nội bộ.Đây sẽ là một giá trị khác khi Roblox chưa hỗ trợ nội bộ bộ định vị của người chơi địa phương.

Mẫu mã

This example demonstrates how to check the locale of a local player using the Player.LocaleId property. It prints a string with the two letter locale code for the locale of the local player.

For instance, if the player's local is within the US, the locale will be:

en-us

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

Tính năng này chỉ có thể được đọc để xác định quyền thành viên (nó không thể được đặt thành đánh máythành viên khác).Nó giữ một Enum.MembershipType danh sách枚 của loại thành đánh máytài khoản.

Mẫu mã

The following example checks whether a player has Premium membership.

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

Thuộc tính NameDisplayDistance StarterPlayer đặt khoảng cách bằng đinh tán ở đó mà người chơi này sẽ nhìn thấy các tên khác Humanoid .Nếu thuộc tính được đặt thành 0, các tên được ẩn.Thuộc tính này được đặt thành StarterPlayer.NameDisplayDistance mặc định.

Nếu thanh sức khỏe của một Humanoid hiển thị, bạn có thể đặt loại hiển thị bằng cách sử dụng Humanoid.DisplayDistanceType .

Mẫu mã

This example demonstrates how to hide other Humanoid's (Player and NPC) health bars and names.

This is done by setting the player's Player.HealthDisplayDistance and Player.NameDisplayDistance properties to 0.

If you would like to display health bars and names, you set the properties to a value greater than 0. For instance, setting the properties to 100 means that the player will see other player's health and names up to 100 studs away.

To modify the default values for players, you can change the values of the StarterClass.Player.HealthDisplayDistance and StarterClass.Player.NameDisplayDistance properties.

Hiding Player Health and Names

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

Neutral

Đọc Song Song

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

  • Khi đúng, người chơi không ở trong một đội cụ thể.Điều này cũng có nghĩa là thuộc tính Player.Team sẽ là nilPlayer.TeamColor sẽ là trắng.
  • Khi giả mạo, người chơi ở trong một đội cụ thể.Thuộc tính Player.Team sẽ tương ứng với Team mà người chơi đang ở, giống như Player.TeamColor .

Mẫu mã

This example checks if a player is neutral. If the player is neutral, the game prints:

Player is neutral!

If the player is not neutral, the game prints:

Player is not neutral!

Note: Although this example prints the value of the local player's neutral property, you can change the example to get the value for any player.

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

ReplicationFocus

Đọc Song Song

Tính năng ReplicationFocus Player tùy chỉnh bộ phận tập trung sao chép xung quanh một Người chơi.Các hệ thống Roblox khác nhau giao tiếp qua mạng (như vật lý, phát trực tiếp, v.v.) sao lưu với tốc độ khác nhau tùy thuộc vào mức độ gần của các đối tượng đối với tập trung sao lưu.

Khi thuộc tính này là nil, nó quay lại hành vi mặc định là điều trị nhân vật của người chơi địa phương PrimaryPart như tâm điểm sao chép.

Thuộc tính này chỉ nên được đặt trên máy chủ với một Script , không phải là LocalScript .Lưu ý rằng thuộc tính này không thay đổi hoặc cập nhật quyền sở hữu mạng của các phần.

Mẫu mã

This example creates a new BasePart and sets the Player's Player.ReplicationFocus to that part.

This demonstrates the functionality of the ReplicationFocus property. You can easily change the part that the focus is set to to change the replication focus.

Setting a Player's Replication Focus

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

Nếu được cài đặt, người chơi sẽ hồi sinh tại điểm SpawnLocation đã cho.Thuộc tính này chỉ có thể được đặt thông qua Luau và phải chứa một tham chiếu đến một SpawnLocation hợp lệ, phải đáp ứng các tiêu chí sau:

Nếu RespawnLocation không được đặt thành một giá trị hợp lệ SpawnLocation thì logic sinh sản mặc định sẽ được áp dụng.Để biết thêm thông tin về chủ đề này, hãy xem trang cho SpawnLocation .

Các lựa chọn thay thế cho RespawnLocation
  • Một Player sẽ xuất hiện từ SpawnLocations thuộc về đội của họ. Trong một số trường hợp, có thể đơn giản hơn để thay đổi Player.Team của người chơi thay vào đó.
  • Thực hiện logic spawn tùy chỉnh riêng của bạn bằng cách sử dụng PVInstance:PivotTo() để di chuyển bằng tay Player.Character .

Mẫu mã

This code sample will set the player to always respawn from the last SpawnLocation they touched. New players will respawn from the SpawnLocation named 'FirstSpawn' until they touch a different SpawnLocation.

This is an alternative to using the AllowTeamChangeOnTouch property to switch SpawnLocations and does not require Teams.

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

Thuộc tính Nhóm là một tham chiếu đến một đối tượng Team trong dịch vụ Teams.Nó xác định đội mà người chơi đang ở; nếu Player không ở trong một đội hoặc có một Player.TeamColor không hợp lệ, thuộc tính này là nil .Khi thuộc tính này được cài đặt, người chơi đã tham gia vào sự kiện Team và sự kiện Team.PlayerAdded trên đội liên quan.Tương tự, Team.PlayerRemoved lửa khi thuộc tính không được xác định từ một Team nhất định.

Mẫu mã

This code sample, although lengthy, is quite simple: detect when a player chats /play, then put them on the "Playing" team. When they die, move them back to the "Spectating" team.

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)

This code sample allows any player to chat "/jointeam " where is the name of a team. It uses string manipulation using string.sub and string.lower to make the command case-insensitive and allow for partial matches. For example, "/jointeam red" will match the team "Red Robins".

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

Thuộc tính TeamColor xác định đội nào mà một Người chơi được liên kết với theo đội đó Team.TeamColor .Thay đổi thuộc tính này sẽ thay đổi Player.Team theo đội nào có cùng BrickColor cho đối tượng của họ Team.TeamColor .Nếu không có đối tượng đội nào có màu sắc đội liên quan, người chơi sẽ không được gán với một đội.

Thường là ý tưởng tốt hơn để đặt Player.Team cho tương ứng Team thay vì sử dụng tính năng này.Thiết lập thuộc tính này thường dẫn đến việc lặp lại cùng một giá trị BrickColor cho một đội nhất định trên nhiều tập lệnh; đây là điều bạn muốn tránh khi tuân theo nguyên tắc "Don't Repeat Yourself" (DRY).

Mẫu mã

This code sample, although lengthy, is quite simple: detect when a player chats /play, then put them on the "Playing" team. When they die, move them back to the "Spectating" team.

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

UserId là một thuộc tính chứa một số nguyên tố đọc chỉ có duy nhất và ổn định xác định mọi tài khoản người dùng trên Roblox.Không giống như Instance.Name của một Người chơi, có thể thay đổi theo tên tài khoảndùng hiện tại của người dùng, giá trị này sẽ không bao giờ thay đổi cho cùng một tài khoản.

Thuộc tính này là cần thiết khi lưu/tải dữ liệu người chơi bằng GlobalDataStores .Sử dụng UserId của người chơi làm chìa khóa kho lưu trữ dữ liệu để mỗi người chơi có một chìa khóa duy nhất.

Mẫu mã

The below example would print the UserId of every user who entered a game.

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

The following code sample gives an example of a 'met the creator' badge system. This script will award a specified badge (BADGE_ID) to anyone who is in a server at the same time as the user associated with OWNER_ID.

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)

This code sample retrieves a player's saved gold from a data store and puts the returned value onto the leaderboard. Note that this sample does not save players' gold — it only loads it.

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

()

Chức năng ClearCharacterAppearance loại bỏ tất cả Accessory , Shirt , Pants , CharacterMeshBodyColors từ người chơi được cho Player.Character .Ngoài ra, nó cũng loại bỏ áo thun Decal trên ngực của người chơi.Màu phần thân của nhân vật và khuôn mặt sẽ không thay đổi.Phương pháp này không làm gì nếu người chơi không có một Nhân vật.

Nó không xóa t-shirts , lưới đầu, hoặc khuôn mặt.


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

Chức năng DistanceFromCharacter Player trả về khoảng cách giữa đầu nhân vật và điểm đã cho Vector3 .Nó trả về 0 nếu người chơi không có Player.Character .

Nó hữu ích khi xác định khoảng cách giữa một người chơi và một đối tượng hoặc vị trí khác trong trò chơi.

Nếu bạn muốn xác định khoảng cách giữa hai ví dụ hoặc vị trí không phải người chơi, bạn có thể sử dụng các theo dõi:


local distance = (position1 - position2).Magnitude

Tham Số

point: Vector3

Vị trí từ đó khoảng cách của người chơi đến được đo lường.

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

Lợi Nhuận

Khoảng cách bằng đinh tán giữa người chơi và vị trí.

Mẫu mã

This example demonstrates how to measure the distance between a player's Player.Character and another location.

This code will print the distance of each player's character from the origin (0, 0, 0):

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

Trả về một từ điển chứa thông tin mô tả cách người chơi tham gia vào trải nghiệm. Từ điển bao gồm bất kỳ một trong các trường sau:


<th>Loại giá trị</th>
<th>Mô tả</th>
</tr>
</thead>
<tbody>
<tr>
<th>NguồnGameId</th>
<td>số</td>
<td>Các lớp <code>Class.DataModel.GameId</code> của trải nghiệm mà <code>Người chơi</code> đã dịch chuyển từ.Chỉ hiện diện nếu người chơi dịch chuyển đến trải nghiệm hiện tại và nếu một máy chủ gọi chức năng dịch chuyển.</td>
</tr>
<tr>
<th>Nơi nguồnId</th>
<td>số</td>
<td>Các thuộc tính <code>Class.DataModel.PlaceId</code> của nơi mà <code>Người chơi</code> đã dịch chuyển từ.Chỉ hiện diện nếu người chơi dịch chuyển đến nơi hiện tại và một máy chủ gọi chức năng dịch chuyển.</td>
</tr>
<tr>
<th>ReferredByPlayerId được đề cập</th>
<td>số</td>
<td>Các lớp <code>Class.Player.UserId</code> của người chơi mời người chơi hiện tại vào trải nghiệm.Sử dụng dữ liệu này để xác định người giới thiệu và kích hoạt logic phần thưởng.</td>
</tr>
<tr>
<th>Thành viên</th>
<td>mảng</td>
<td>Một mảng chứa các số <code>Class.Player.UserId</code> của người dùng đã dịch chuyển cùng với <code>Người chơi</code>.Chỉ hiện diện nếu người chơi đã dịch chuyển làm phần của một nhóm.</td>
</tr>
<tr>
<th>Dữ liệu dịch chuyển</th>
<td>biến thể</td>
<td>Phản ánh <code>teleportData</code> được định nghĩa trong teleport ban đầu.Hữu ích để chia sẻ thông tin giữa các máy chủ mà người chơi dịch chuyển đến.Chỉ có mặt nếu <code>teleportData</code> được định nghĩa và một máy chủ gọi chức năng teleport.</td>
</tr>
<tr>
<th>Dữ liệu khởi chạy</th>
<td>chuỗi</td>
<td>Một chuỗi được mã hóa thông thường hoặc JSON chứa dữ liệu khởi động được xác định trong một <a href="../../../production/promotion/deeplinks.md">liên kết sâu</a> URL hoặc <code>Class.ExperienceInviteOptions.LaunchData</code>.</td>
</tr>
<tr>
<th>GameJoinContext</th><td>từ điển</td>
<td>
Một từ điển bao gồm thông tin liên quan dựa trên bối cảnh tham gia trò chơi. Nó bao gồm các chìa khóa sau:
<ul>
<li><code>JoinSource</code> : <code>Enum.JoinSource</code> ></li><li><code>ItemType</code> : tùy chọn <code>Enum.AvatarItemType</code></li><li><code>AssetId</code> : tùy chọn <code>string</code></li><li><code>OutfitId</code> : tùy chọn <code>string</code></li><li><code>AssetType</code> : tùy chọn <code>Enum.AssetType</code></li>
</ul>
</td>
</tr>
</tbody>
Nhân vật chính

Nhận GetJoinData và TeleportData

Nếu một máy chủ khởi động dịch chuyển của Người chơi, từ điển mà phương thức này trả về bao gồm dữ liệu dịch chuyển của Người người chơi.Phương pháp Player:GetJoinData() chỉ có thể được sử dụng để lấy dữ liệu dịch chuyển trên máy chủ.Để lấy dữ liệu trên máy khách, sử dụng TeleportService:GetLocalPlayerTeleportData() .

Không giống như TeleportService:GetLocalPlayerTeleportData() , Player:GetJoinData() chỉ cung cấp dữ liệu dịch chuyển đáp ứng các tiêu chí bảo mật sau:

  • Nó được đảm bảo đã được gửi bởi một máy chủ Roblox trong vòng 48 giờ qua.
  • Nó được đảm bảo đã được gửi với cái này Player .
  • The SourcePlaceIdSourceGameId được đảm bảo là nơi và vũ trụ dữ liệu được gửi từ.Điều này có nghĩa là bạn có thể xác minh dữ liệu dịch chuyển đến từ một địa điểmđược phê duyệt.

Vì dữ liệu này được gửi bởi khách hàng, nó vẫn có thể bị lạm dụng bởi một kẻ lừa đảo.Dữ liệu nhạy cảm như tiền tệ người chơi nên được truyền qua giải pháp an toàn như Kho lưu trữ bộ nhớ.


Lợi Nhuận

Một từ điển chứa các giá trị PlaceId và UserId (xem bảng trong phần mô miêu tả).

Mẫu mã

The following example tracks sources of traffic for analytics. By creating URLs with unique launch data for each social platform, you can determine the most popular traffic sources. The sample checks the source against a list of possible samples and discards any invalid sources because users can modify the launch data.

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)

The following example generates a URL with the user's ID used as launch data. It then displays the URL in a read-only text box that makes it easy for the user to copy and share the link with their friends. When a user joins the game using a referral link, you can use the launch data to reward the referrer.

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)

The following example is a function that converts a table into a string you can use as launch data. The provided data is JSON encoded, checked for valid character length, and escaped with percent signs.

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

The following example attempts to decode launch data, using pcall to prevent an error in case the data is corrupt.

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)

The following code sample is an example of how teleport data can be retrieved on the server using Player:GetJoinData(). This code, when ran in a Script in ServerScriptService, will listen for new Player|Players joining the game. When they join it will retrieve their teleport data (verifying it came from a valid place) to find their current level.

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

Chức năng GetMouse Player trả về Mouse đang được sử dụng bởi khách hàng.Instanza chuột của người chơi có thể được sử dụng để theo dõi lượt nhấp chuột người dùng bao gồm các nhấp chuột nút chuột trái và phải và di chuyển và vị trí.

Dịch vụ UserInputService cung cấp thêm chức năng và sự kiện để theo dõi nhập của người dùng - đặc biệt là đối với các thiết bị không sử dụng chuột.

Ghi chú:

  • Vật phẩm này phải được sử dụng trong LocalScript để hoạt động như mong đợi trực tuyến.
  • Sau khi cập nhật vào tháng 7 năm 2014, biểu tượng của chuột có thể được đặt bằng phương pháp này.

Lợi Nhuận

Mẫu mã

The below example will print:

Button 1 is down

whenever the Players.LocalPlayer left clicks.

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

Nhận mạng Ping trả về thời gian trễ mạng cách ly của Player trong giây lát.“Ping” là một đo lường thời gian mà dữ liệu được gửi từ khách hàng đến máy chủ, sau đó trở lại.Nó không liên quan đến giải mã hoặc xử lý dữ liệu.

Đối với phía khách LocalScripts, chức năng này chỉ có thể được gọi trên Players.LocalPlayer.Chức năng này hữu ích trong việc xác định và gỡ lỗi các vấn đề xảy ra trong các tình huống độ trễ mạng cao.Nó cũng hữu ích để che khuất thời gian trễ, chẳng hạn như điều chỉnh tốc độ ném hoạt hình cho các viên đạn.


Lợi Nhuận

HasAppearanceLoaded

Chức năng HasAppearanceLoaded Player trả về xem có hay không có sự xuất hiện của Player.Character người chơi đã được tải.

Sự xuất hiện của một người chơi bao gồm các vật phẩm như người chơi của người chơi Shirt , PantsAccessories .

Điều này hữu ích khi xác định xem liệu sự xuất hiện của một người chơi đã được tải sau khi họ tham gia trò chơi lần đầu tiên, có thể được theo dõi bằng sự kiện Players.PlayerAdded.


Lợi Nhuận

Một boolean chỉ ra liệu 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.

Mẫu mã

This example prints the result of Player:HasAppearanceLoaded() after a player joins the game until the player's appearance has loaded.

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

Trả về một giá trị boolean chỉ ra tình trạng tháixác minh của người chơi.Khi đúng, người chơi được xác minh.Xác minh bao gồm, nhưng không giới hạn, số điện thoại không phải là VOIP hoặc xác minh ID chính phủ.

Khi thực hiện IsVerified, thực hiện cẩn thận để đảm bảo rằng triển khai không vô tình chặn tất cả các người dùng chưa được xác minh.

Lưu ý rằng phương thức chỉ có thể được gọi trên máy chủ backend.Gọi nó kết quả bên khách trong một lỗi.Ngoài ra, phương pháp này sẽ luôn luôn trả về false trong Studio.


Lợi Nhuận

Một boolean chỉ ra xem người chơi có được xác minh hay không.

Mẫu mã

The following example prints "true" if the player is verified.

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

()

Phương pháp Kick() cho phép một trải nghiệm kết nối lại một khách hàng một cách thanh lịch và có thể cung cấp một tin nhắn cho người dùng bị tách khỏi.Điều này hữu ích để kiểm soát người dùng lạm dụng.Bạn chỉ nên cho phép các người dùng cụ thể mà bạn tin tưởng kích hoạt phương pháp này trên các người dùng khác.

Gọi phương thức này trên một Player với không có tham số sẽ ngắt kết nối người dùng với máy chủ và cung cấp một thông báo cảnh báo mặc định.Gọi phương thức này trên một Player cùng với một chuỗi như là tham số đầu tiên thay thế tin nhắn mặc định bằng chuỗi cung cấp.

Khi sử dụng phương pháp này từ một LocalScript , chỉ khách hàng của người dùng địa phương có thể bị đuổi.

Tham Số

message: string

Tin nhắn để hiển thị người dùng khi đá.

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

Lợi Nhuận

()

Move

()

Chức năng di chuyển Player khiến 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ọ).

Điều này hữu ích khi lập trình NPC Humanoids di chuyển xung quanh bản đồ - nhưng không được kiểm soát bởi đầu vào của người chơi thực tế.

Lưu ý rằng tham số thứ hai của chức năng chỉ ra xem liệu đầu vào được cung cấp có nên di chuyển người chơi theo phối trí thế giới ( false ) hay không ( true ).

Tham Số

walkDirection: Vector3

Hướng Vector3 mà người chơi nên di chuyển.

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

Một boolean chỉ ra liệu người chơi có nên di chuyển so với camera của người chơi hay không.

Giá Trị Mặc Định: false

Lợi Nhuận

()

Mẫu mã

Demonstrates moving a player relative to their camera's position using Player:Move().

The script first waits for the player's Character and Humanoid to load, as both are required before calling Player:Move(). Otherwise a warning will display in the Output.

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

Chức năng SetAccountAge đặt Player.AccountAge của người chơi trong các ngày.

Nó được sử dụng để đặt thuộc tính Player mô tả thời gian trước khi tài khoản của một người chơi được đăng ký trong các ngày.

Điều này không đặt tuổi của người chơi trên tài khoản, nhưng tuổi của tài khoản chính mình so với khi nó được tạo lần đầu tiên.

Tham Số

accountAge: number

Tuổi của tài khoản trong ngày.

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

Lợi Nhuận

()

Mẫu mã

This example demonstrates how the Player:SetAccountAge() function would be used if it was accessible. It sets the local player's account age to 100 days.

Setting the Player's Account Age

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player:SetAccountAge(100)

This code sample adds a mark to players showing about how old their account is. The mark uses a player's account age to determine if they are a New Player, Veteran Player or Regular Player.

Account Age Mark

local Players = game:GetService("Players")
local MAX_AGE_NEW_PLAYER = 7 -- one week
local MIN_AGE_VETERAN = 365 -- one year
-- This function marks a part with text using a 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) -- Fill parent
textLabel.Text = text
textLabel.TextColor3 = Color3.new(1, 1, 1)
textLabel.TextStrokeTransparency = 0
textLabel.BackgroundTransparency = 1
textLabel.Parent = bbgui
-- Add to part
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)
-- Listen for this player spawning
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

Phương pháp này xác định xem người chơi có nhìn thấy trò chuyện bị lọc bởi TextService:FilterStringAsync() hay không so với trò chuyện bình thường.


local Players = game:GetService("Players")
local player = Players.LocalPlayer
player:SetSuperSafeChat(true)

Bất kể người chơi có bật lọc trò chuyện hay không, tất cả các cuộc trò chuyện nên được lọc bởi TextService khi phát sóng cho người chơi khác hoặc trên màn hình của người chơi.TextService:FilterStringAsync() trả về một đối tượng TextFilterResult có thể được lọc khác nhau tùy theo mục đích sử dụng của tin nhắn.

Tham Số

value: boolean

Một boolean chỉ ra liệu người chơi có nhìn thấy trò chuyện lọc hay không.

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

Lợi Nhuận

()

GetFriendsOnline

Sinh Lợi

Chức năng này trả về một mảng danh sách bạn bè trực tuyến, bị giới hạn bởi giá trị maxFriends. Chức năng sử dụng một bộ nhớ đệm 30 giây.

Trong mảng trả về, một số trường chỉ có mặt ở một số loại vị trí nhất định.Ví dụ, PlaceId sẽ không có mặt khi LocationType là 0 (Trang web di động).


<th>Loại</th>
<th>Mô tả</th>
</tr>
</thead>
<tbody>
<tr>
<td><b>ID khách truy cập</b></td>
<td>số</td>
<td>Các lớp <code>Class.Player.UserId</code> của bạn bè.</td>
</tr>
<tr>
<td><b>Tên người dùng</b></td>
<td>chuỗi</td>
<td>Tên người bạn bè.</td>
</tr>
<tr>
<td><b>Tên hiển thị</b></td>
<td>chuỗi</td>
<td>Các lớp <code>Class.Player.DisplayName</code> của bạn bè.</td>
</tr>
<tr>
<td><b>Trực tuyến cuối cùng</b></td>
<td>chuỗi</td>
<td>Khi bạn bè lần cuối trực tuyến.</td>
</tr>
<tr>
<td><b>Đang trực tuyến</b></td>
<td>boolean như vậy</td>
<td>Nếu bạn bè hiện đang trực tuyến.</td>
</tr>
<tr>
<td><b>Vị trí cuối cùng</b></td>
<td>chuỗi</td>
<td>Tên của vị trí hiện tại của bạn bè.</td>
</tr>
<tr>
<td><b>ID nơi</b></td>
<td>số</td>
<td>ID địa điểm của vị trí cuối cùng của bạn bè.</td>
</tr>
<tr>
<td><b>ID trò chơi</b></td>
<td>chuỗi</td>
<td>Cấu trúc <code>DataModel/JobId</code> của vị trí cuối cùng của bạn bè.</td>
</tr>
<tr>
<td><b>Loại vị trí</b></td><td>số</td>
<td>
Loại vị trí cuối cùng của bạn bè: 0 Trang web di động > > Trò chơi trên thiết bị di động > > Ứng dụng trên thiết bị di động > > Trang web trên máy tính bảng > > Ứng dụng trên máy tính bảng > > Trình duyệt web trên thiết bị di động Ứng dụng trên thiết bị di động trên máy tính bảng trình duyển trên thiết bảng trên máy tính trên trình duyển ứng trên thiết trên trình duyển vị trình trên thiết trên máy tính trên trình trên máy trình duyển trên máy trên trình trên trình trên trình trên trình trên trình trên máy trên trình trên trình trên trình trên trình trên trình trên trình trên trình trên trình trên trình trên trình trên trên trình trên trình trên trình trên trên trình trên trình trên trình trên trình trên trình trên trình trên trình trên trên trình trên trình trên trì trên trên trì trên trên trì trên trì trên trì trên trì trên trì trì trên trì trên trì trên trì trên trên trì trên trì trên trì trì trì trì trì trì trì trên trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì trì tr
</td>
</tr>
</tbody>
Tên

Tham Số

maxFriends: number

Số lượng bạn bè trực tuyến tối đa để trả lại.

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

Lợi Nhuận

Một từ điển của bạn bè trực tuyến (xem bảng trên).

Mẫu mã

This example demonstrates how to get a dictionary of a player's online friends. It returns the maximum number of friends specified by the argument, or 200 if an argument is not provided.

Get a List of Online Friends

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

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

Sử dụng cái này trong một Script , so với một LocalScript , sẽ không cho bạn thông tin mới nhất.Nếu một người chơi rời khỏi nhóm trong khi họ đang ở trong trò chơi, GetRankInGroup vẫn sẽ nghĩ rằng họ ở trong nhóm đó cho đến khi họ rời đi.Tuy nhiên, điều này không xảy ra khi sử dụng với một LocalScript.

Điều này là do cách thức lưu trữ kết quả của phương pháp, vì vậy nhiều lần gọi GetRankInGroup trên cùng một người chơi với cùng một ID nhóm sẽ cho kết quả tương tự như khi phương pháp được gọi lần đầu tiên với ID nhóm đã cho.Hành vi lưu trữ là trên cơ sở mỗi cặp: một máy chủ không chia sẻ cùng một bộ nhớ lưu trữ với một khách hàng.

Tham Số

groupId: number

The groupId của nhóm được chỉ định.

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

Lợi Nhuận

Hạng của người chơi trong nhóm.

Mẫu mã

The code below will check if a player that has entered the game has a rank equal to 255, in a group with an ID of 2. If they are, it will print "Player is the owner of the group, 'LOL'!", otherwise "Player is NOT the owner of the group, 'LOL'!" will be printed to the output.

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

Chức năng GetRoleInGroup Player trả về vai trò của người chơi trong nhóm dưới dạng chuỗi, hoặc Khách mời nếu người chơi không thuộc nhóm.

Sử dụng cái này trong một Script , so với một LocalScript , sẽ không cho bạn thông tin mới nhất.Nếu một người chơi rời khỏi nhóm trong khi họ đang ở trong trò chơi, GetRoleInGroup vẫn sẽ nghĩ rằng họ ở trong nhóm đó cho đến khi họ rời đi.Tuy nhiên, điều này không xảy ra khi sử dụng với một LocalScript.

Điều này là do cách thức lưu trữ kết quả của phương pháp, vì vậy nhiều lần gọi GetRoleInGroup trên cùng một người chơi với cùng một ID nhóm sẽ cho kết quả tương tự như khi phương pháp được gọi lần đầu tiên với ID nhóm đã cho.Hành vi lưu trữ là trên cơ sở mỗi cặp: một máy chủ không chia sẻ cùng một bộ nhớ lưu trữ với một khách hàng.

Tham Số

groupId: number

The groupId của nhóm được chỉ định.

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

Lợi Nhuận

Vai trò của người chơi trong nhóm được chỉ định, hoặc Khách nếu người chơi không phải là thành viên.

Mẫu mã

The code below will print the name of the rank that the player is currently a part of, in a specific group. In this instance we're checking what rank the player is within a group which has a group ID of 2.

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

Chức năng này gửi yêu cầu đến trang web Roblox hỏi liệu người chơi có phải là bạn bè của người dùng khác, dựa trên Player.UserId của người dùng đó.Chức năng này lưu trữ kết quả nên nhiều lần gọi chức năng trên cùng một người chơi với cùng một Player.UserId không thể cho ra kết quả mới nhất.Điều này không xảy ra khi sử dụng trong một LocalScript .

Tham Số

userId: number

The Player.UserId của người chơi được chỉ định.

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

Lợi Nhuận

Một boolean chỉ ra xem một người chơi có phải là bạn của người dùng được chỉ định hay không.

Mẫu mã

The below example would print whether or not a recently added player is friends with Gordonrox24.

How to Check if a Player is a Friend

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

IsInGroup

Sinh Lợi

Chức năng IsInGroup Player gửi yêu cầu đến trang web Roblox hỏi liệu người chơi có phải là thành viên của một nhóm hay không, dựa trên ID của nhóm đó.

Sử dụng cái này trong một Script , so với một LocalScript , sẽ không cho bạn thông tin mới nhất.Nếu một người chơi rời khỏi nhóm trong khi họ đang ở trong trò chơi, IsInGroup vẫn sẽ nghĩ rằng họ đang ở trong nhóm cho đến khi họ rời đi.Tuy nhiên, điều này không xảy ra khi sử dụng với một LocalScript.

Điều này là do cách thức lưu trữ kết quả của phương pháp, vì vậy nhiều lần gọi IsInGroup trên cùng một người chơi với cùng một ID nhóm sẽ cho kết quả tương tự như khi phương pháp được gọi lần đầu tiên với ID nhóm đã cho.Hành vi lưu trữ là trên cơ sở mỗi cặp: một máy chủ không chia sẻ cùng một bộ nhớ lưu trữ với một khách hàng.

Tham Số

groupId: number

The groupId của nhóm được chỉ định.

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

Lợi Nhuận

Một boolean chỉ ra xem người chơi có ở trong nhóm được chỉ định hay không.

Mẫu mã

The below example will print "Player is in the Roblox Fan club!" if the newly added player is in the group with a groupId of 7.

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

Chức năng LoadCharacter Player tạo ra một nhân vật mới cho người chơi, loại bỏ cái cũ.Nó cũng xóa BackpackPlayerGui của người chơi.

Điều này hữu ích trong trường hợp bạn muốn tải lại nhân vật mà không giết người chơi, chẳng hạn như khi bạn muốn tải xuất một hình xuất hiện nhân vật mới sau khi thay đổi hình ảnh người chơi Player.CharacterAppearance.

Lưu ý: Chức năng tương tự như Player:LoadCharacterBlocking(), nhưng yêu cầu được xử lý song song thay vì đồng bộ.Điều này có nghĩa là các nhiệm vụ khác sẽ có thể tiếp tục khi nhân vật đang được tải, bao gồm cả việc hiển thị trò chơi và bất kỳ nhiệm vụ nào khác.Ngoài ra, chức năng này có thể được sử dụng trong một kịch bản, trong khi LoadCharacterBlocking không thể.

Sau khi gọi LoadCharacter cho một người chơi cá nhân, không được khuyến khích gọi lại cho cùng một người chơi cho đến khi sự kiện Player.CharacterAppearanceLoaded của người chơi đó đã bắt lửa.

Sự kiện tải nhân vật

Gọi Player:LoadCharacter() với một Avatar R15 kích hoạt sự kiện theo thứ tự sau (Lưu ý: việc xếp hạng R6 khác nhau):

  1. Bộ nhân vật Player.Character
  2. Người chơi.CharacterAdded bắn
  3. Người chơi.Changed bắt lửa với giá trị "Nhân vật"
  4. Khởi tạo xuất hiện nhân vật
  5. Các lỗi Player.CharacterAppearanceLoaded
  6. Nhân vật.Parent đặt vào DataModel
  7. Các mô hình nhân vật được xây dựng và kích thước nhân vật
  8. Nhân vật di chuyển đến vị trí sinh sản
  9. Trả về LoadCharacter

Lợi Nhuận

()

Mẫu mã

This script turns off auto-loading and simulates character respawning.

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

Chức năng này tạo ra một avatar để nó có mọi thứ được trang bị trong đã truyền ở HumanoidDescription .

Sau khi gọi LoadCharacterWithHumanoidDescription cho một người chơi cá nhân, không được khuyến khích gọi lại chức năng cho cùng một người chơi cho đến khi sự kiện Player.CharacterAppearanceLoaded của người chơi đó đã bắt lửa.

Xem thêm:

  • Hệ thống Mô tả Nhân tạo , một bài báo giải thích hệ thống mô tả nhân tạo chi tiết hơn và cung cấp một số ví dụ lập trình

Tham Số

humanoidDescription: HumanoidDescription

Một HumanoidDescription chứa các đặc điểm như các bộ phận cơ thể/màu sắc, thay đổi kích thước cơ thể, phụ kiện, quần trạng phụcvà hoạt hình sẽ được trang bị cho nhân vật đã tải.

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

Lợi Nhuận

()

Mẫu mã

To create a HumanoidDescription and then spawn a character with that description applied, add a Script (not a LocalScript) to the workspace and add this code to it.

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

Đối với trải nghiệm mà instance phát trực tuyến được bật, các yêu cầu yêu cầu máy chủ phát đến các khu vực người chơi (phần và địa hình) xung quanh vị trí X , Y , Z được chỉ định trong thế giới 3D.Nó hữu ích nếu trải nghiệm biết rằng CFrame của người chơi sẽ được đặt vào vị trí đã định trong tương lai gần.Không cung cấp vị trí với cuộc gọi này, người chơi có thể không đã phát trực tiếp trong nội dung cho điểm đến, dẫn đến tạm dừng phát trực tiếp hoặc hành vi không mong muốn khác.

Hiệu ứng của cuộc gọi này sẽ tạm thời và không có bảo đảm về những gì sẽ được phát trực tiếp xung quanh vị trí được chỉ định.Giới hạn bộ nhớ khách hàng và điều kiện mạng có thể ảnh hưởng đến những gì sẽ có sẵn trên khách hàng.

Cảnh báo sử dụng

Yêu cầu phát trực tuyến xung quanh khu vực là không có bảo đảm rằng nội dung sẽ có mặt khi yêu cầu hoàn thành, bởi vì phát trực tuyến bị ảnh hưởng bởi băng thông mạng của khách hàng, giới hạn bộ nhớ và các yếu tố khác.

Tham Số

position: Vector3

Vị trí thế giới mà phát trực tuyến được yêu cầu.

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

Thời gian chờ tùy chọn cho yêu cầu.

Giá Trị Mặc Định: 0

Lợi Nhuận

()

Sự Kiện

CharacterAdded

Sự kiện Tính nhân vật được thêm bắt lửa khi nhân vật của một người chơi xuất hiện (hoặc tái sinh).Sự kiện này xảy ra ngay sau khi đặt Player.Character đến giá trị không nil hoặc gọi Player:LoadCharacter() , trước khi nhân vật được gán cho Workspace .

Điều này có thể được sử dụng cùng với sự kiện Player.CharacterRemoving , được kích hoạt ngay trước khi nhân vật của người chơi sắp bị xóa, thường là sau khi chết.Do đó, cả hai sự kiện này có thể tiềm ẩn bắt lửa nhiều lần khi người chơi chết rồi hồi sinh ở một địa điểm.Nếu bạn muốn phát hiện khi một người chơi tham gia hoặc rời khỏi trò chơi, hãy sử dụng sự kiện Players.PlayerAddedPlayers.PlayerRemoving thay vào đó.

Lưu ý rằng Humanoid và các phần thân thể mặc định (đầu, thân và chi) sẽ tồn tại khi sự kiện này bắt lửa, nhưng các mặt hàng quần áo như Hats , ShirtsPants có thể mất vài giây để được thêm vào nhân vật.Kết nối Instance.ChildAdded trên nhân vật được thêm vào để phát hiện chúng, hoặc chờ sự kiện Player.CharacterAppearanceLoaded để chắc chắn rằng nhân vật đã được trang bị đầy đủ.

Tham Số

character: Model

Một ví dụ về nhân vật đã sinh ra/hồi sinh.


Mẫu mã

This code sample demonstrates the usage of Players.PlayerAdded, Player.CharacterAdded and Player.CharacterRemoving in order to detect the spawning and despawning of players' characters. You can use this as a boilerplate script to make changes to players' characters as they spawn, such as changing Humanoid.WalkSpeed.

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)

This code sample will cause players to respawn at the same place they died. It does this by keeping track of where the player despawned using Player.CharacterRemoving. Note that the player's location is saved on-despawn, not on-death. This can be problematic if the player falls off a ledge and dies due to Workspace.FallenPartsDestroyHeight - their respawn position won't be saved in this case.

It's also important to note the need to "forget" the location of players who leave the game. We use Instance.ChildRemoved on Players instead of Players.PlayerRemoving. This is because PlayerRemoving fires before CharacterRemoving - and we need to make sure we don't forget the player's respawn location then immediately remember a new one (this is a memory leak; potentially many players could visit, respawn and leave). So, we use ChildRemoved on Players so the event fires after the character is removed.

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)

This code sample automatically removes Accessory objects like hats from the Player's character when they respawn. Warning: this includes hair, so this script may cause acute baldness.

When the Character() is added, we wait for RunService.Stepped to fire once (using the wait function of events). This is so the accessory removal logic runs one frame after the character spawns. A warning can appear if you delete accessories too quickly after the player spawns, so waiting one frame will avoid that.

Accessory Remover

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)
-- Wait a brief moment before removing accessories to avoid the
-- "Something unexpectedly set ___ parent to NULL" warning
RunService.Stepped:Wait()
-- Check for any existing accessories in the player's character
for _, child in pairs(character:GetChildren()) do
destroyAccessory(child)
end
-- Hats may be added to the character a moment after
-- CharacterAdded fires, so we listen for those using ChildAdded
character.ChildAdded:Connect(destroyAccessory)
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(onCharacterAdded)
end
Players.PlayerAdded:Connect(onPlayerAdded)

CharacterAppearanceLoaded

Sự kiện này bắt lửa khi toàn bộ xuất hiện của một Player.Character đã được chèn vào.

A Player.Character thường có một loạt các đối tượng sửa đổi sự xuất ngoại hìnhcủa nó, bao gồm Accoutrements , Shirts , PantsCharacterMeshes .Sự kiện này sẽ bắt lửa khi tất cả các đối tượng như vậy đã được chèn vào Player.Character .

Sự kiện này chỉ bắt lửa trên máy chủ.

Một lần sử dụng cho sự kiện này là đảm bảo tất cả các phụ kiện đã được tải trước khi phá hủy chúng. Xem dưới đây để có một ví dụ về điều này.

Tham Số

character: Model

Các Class.Player.Character``Class.Model .


Mẫu mã

This code sample will wait for accessories to fully load, print out how many there are, and then destroy them all.

Remove Accessories After Loading

local Players = game:GetService("Players")
local function onPlayerAddedAsync(player)
local connection = player.CharacterAppearanceLoaded:Connect(function(character)
-- All accessories have loaded at this point
local humanoid = character:FindFirstChildOfClass("Humanoid")
local numAccessories = #humanoid:GetAccessories()
print(("Destroying %d accessories for %s"):format(numAccessories, player.Name))
humanoid:RemoveAccessories()
end)
-- Make sure we disconnect our connection to the player after they leave
-- to allow the player to get garbage collected
player.AncestryChanged:Wait()
connection:Disconnect()
end
for _, player in Players:GetPlayers() do
task.spawn(onPlayerAddedAsync, player)
end
Players.PlayerAdded:Connect(onPlayerAddedAsync)

CharacterRemoving

Sự kiện Loại bỏ nhân vật xảy ra ngay trước khi nhân vật của người chơi bị xóa, chẳng hạn như khi người chơi đang hồi sinh.

Sự kiện này có thể được sử dụng cùng với sự kiện Player.CharacterAdded, bắn khi nhân vật của người chơi xuất hiện hoặc hồi sinh.Ví ví dụ / trường hợp, nếu bạn muốn in một tin nhắn mỗi khi một người chơi xuất hiện và chết:


local Players = game:GetService("Players")
local function onCharacterSpawned(player)
print(player.Name .. " is spawning")
end
local function onCharacterDespawned(player)
print(player.Name .. " is despawning")
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(function()
onCharacterSpawned(player)
end)
player.CharacterRemoving:Connect(function()
onCharacterDespawned(player)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)

Sự kiện này chỉ quan tâm đến Character của một Player.Nếu bạn cần theo dõi khi một người chơi tham gia/rời khỏi trò chơi, hãy sử dụng sự kiện Players.PlayerAddedPlayers.PlayerRemoving .

Tham Số

character: Model

Một ví dụ về nhân vật đang bị xóa.


Mẫu mã

This example prints the name of the character being removed, followed by "has died".

For instance, if Shedletsky's character was to die in-game, "Shedletsky has died." would be printed.

Player.CharacterRemoving

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

Chatted

Sự kiện Trò chuyện bắt lửa khi một Player loại tin nhắn nhập và nhấn Enter vào thanh trò chuyện cung cấp của Roblox.Điều này được thực hiện bằng cách sử dụng một số giao diện Luau bởi kịch bản trò chuyện mặc định.Bạn có thể ngăn người chơi trò chuyện bằng cách sử dụng StarterGui:SetCoreGuiEnabled() và vô hiệu hóa trò chuyện Enum.CoreGuiType .

Lệnh trò chuyện

Sử dụng sự kiện này và một số chức năng thao tác chuỗi như string.sub()string.lower(), bạn có thể tạo lệnh trò chuyện, ngay cả với các tham số như tên người chơi.Thông thường, các lệnh được đặt trước bằng chữ cái như heal PlayerName .Để kiểm tra một chữ đầu trong một chuỗi, sử dụng string.sub() trên tin nhắn để kiểm tra một phần của tin nhắn: string.sub(message, 1, 6) == "/heal " (lưu ý bao gồm không gian).Sau đó, chiết xuất phần còn lại của lệnh bằng cách sử dụng string.sub() một lần nữa: string.sub(message, 7) sẽ bằng với tên người chơi.Kiểm tra xem người chơi đó có tồn tại hay không, và nếu có, thực hiện hành động của lệnh (trong ví dụ này, hồi máu cho họ).Kiểm tra các mẫu mã code để xem ví dụ về lệnh trò chuyện.

Lọc

Văn bản tin nhắn bị bắn với sự kiện này là chưa lọc .Nếu bạn đang hiển thị nhập của người chơi như trò chuyện với người chơi khác trong bất kỳ hình thức nào, nó phải được lọc bằng Chat:FilterStringAsync() .Hãy nhớ điều này khi tạo các hệ thống trò chuyện riêng của bạn; nếu trò chơi của bạn không lọc trò chuyện đúng cách, nó có thể bị thực hiện hành động kiểm duyệt chống lại nó.

Tham Số

message: string

Nội dung tin nhắn mà người chơi đã gõ vào trò chuyện.

recipient: Player

Bị loại bỏ. Đối với tin nhắn thì thầm, đây là người chơi là mục tiêu dự định của tin nhắn trò chuyện.


Mẫu mã

Setting chatted for all players. There is an easy way to make the Chatted event registered on all players. Simply use the Players.PlayerAdded event in combination with this event.

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)

This code sample, although lengthy, is quite simple: detect when a player chats /play, then put them on the "Playing" team. When they die, move them back to the "Spectating" team.

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)

This code sample allows any player to chat "/jointeam " where is the name of a team. It uses string manipulation using string.sub and string.lower to make the command case-insensitive and allow for partial matches. For example, "/jointeam red" will match the team "Red Robins".

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

Sự kiện này bắt lửa khoảng hai phút sau khi lớp động cơ trò chơi xếp hạng player là nhàn rỗi.Thời gian là số giây đã trôi qua kể từ điểm đó.Sự kiện tiếp tục bắn mỗi 30 giây miễn là người chơi vẫn còn nhàn rỗi.

Sự kiện này chỉ bắt lửa trong các kịch bản khách, không phải kịch bản máy chủ; sử dụng một RemoteEvent để thông báo cho máy chủ về các người chơi rảnh rỗi.

Roblox tự động ngắt kết nối với người chơi đã không hoạt động trong ít nhất 20 phút, vì vậy sự kiện này hữu ích để cảnh báo người chơi rằng họ sẽ bị ngắt kết nối sớm, ngắt kết nối người chơi trước khi 20 phút đó, hoặc các tính năng khác ra khỏi bàn phím (AFK).

Để theo dõi số lần tắt máy tự động xảy ra thường xuyên, hãy thử liên kết sự kiện này với các sự kiện của Players.PlayerRemoving .

Tham Số

time: number

Thời gian bằng giây mà người chơi đã nhàn rỗi.


Mẫu mã

Prints how long a player has been idle for.

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

Bị bắn khi tình trạng dịch chuyển của một người chơi thay đổi. Sự kiện này hữu ích để phát hiện xem dịch chuyển có thành công hay không.

TeleportState là gì?

Khi yêu cầu dịch chuyển được thực hiện bằng cách sử dụng TeleportService, có một loạt các giai đoạn trước khi Player được dịch chuyển.Giai đoạn hiện tại được đại diện bởi giá trị Enum.TeleportState được cung cấp bởi OnTeleport.Xem phía dưới để có một ví dụ thực tế về điều này.

Tham Số

teleportState: Enum.TeleportState

Cái mới Enum.TeleportState của Player .

placeId: number

ID của nơi mà Player đang được dịch chuyển đến.

spawnName: string

Tên của spawn để dịch chuyển đến, nếu TeleportService:TeleportToSpawnByName() đã được sử dụng.


Mẫu mã

This example prints which stage of a teleport a player is at, as well as printing if the teleport was a failure.

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)