一個 玩家 對象是目前連接的客戶。這些對象會在新玩家連接時添加到 Players 服務,然後當他們最終從伺服器中斷連線時移除。
Instance.Name 屬性反映了玩家的用戶名。當儲存關於玩家的資訊時,您應該使用他們的 Player.UserId ,因為玩家可能會更改他們的使用者名稱。
在 Players 服務中有許多與玩家對象相關的類似方法。使用它們超過其各自的 Instance 方法:
- 你可以使用 Players:GetPlayers() 來獲得當前玩家對象的表;再次,使用這個而不是 Instance:GetChildren() 。
- 相同地,您可以使用 偵測玩家對象的移除,該操作在玩家被移除之前發生(而不是在玩家被移除之後發生的 )。如果您正在儲存可能在移除時刪除或清理的玩家資訊,這很重要。
範例程式碼
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.
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)
概要
屬性
描述玩家的帳戶年齡以天為單位。
決定使用移動裝置的玩家角色在撞擊障礙物時會自動跳躍。
玩家的相機允許縮小放的最大距離。
玩家的相機允許放大放的最小距離。
將相攝影機模式變更為第一或第三人稱。
決定角色是否在玩家生成時載入外觀。如果為 false,玩家將生成與預設外觀一樣的外觀。
決定使用玩家的角色外觀的帳戶的使用者ID,該帳戶的角色外觀用於玩家的character。
設置預設攝影機如何處理攝影機和玩家之間的物件。
當使用 Roblox 的桌面版本時,決定玩家的攝影機移動模式。
決定使用 Roblox 桌面版時玩家的角色移動模式。
決定玩家是否可以切換鼠標鎖定。
當使用觸摸裝置時,決定玩家的攝影機移動模式。
當使用觸摸裝置時,決定玩家的角色移動模式。
與玩家相關的使用者ID的顯示名稱。
描述玩家跟隨玩家進入遊戲的玩家的使用者ID。
玩家端遊戲是否目前已暫停。
指示玩家是否有已驗證的徽章。
設置此玩家會看到其他人形的生命條距離。如果設為 0,生命條將不會顯示。
此屬性顯示本地玩家為他們的 Roblox 帳號戶設置的本地 ID。
描述帳帳號的會員輸入。
設置此玩家可以看到其他人形名稱的距離。如果設為 0,名稱將被隱藏。
決定玩家是否在特定團隊上。
將零件設為圍繞重複聚焦。
如果設定,玩家將在指定的 SpawnLocation 重生。
決定玩家與哪個團隊相關。
決定玩家與哪個團隊相關。
一個獨特的識別整數,分配給所有使用者帳戶。
方法
從玩家的角色中移除所有配件和其他角色外觀對象。
返回角色頭和給定的 Vector3 點之間的距離。如果玩家沒有角色,返回 0。
返回包含說明如何 Player 加入體驗的辭典。
返回客戶使用的鼠標。
返回隔離網路延遲時間(秒)。
返回玩家角色的外觀是否已載入。
返回玩家是否使用具體、實世信號進行驗證。
強制從遊戲中斷玩家,可選擇提供訊息。
讓玩家的角色在指定的方向走動,直到被停止或由玩家中斷(使用他們的控制件)為止。
設置玩家的帳戶年齡。
設置玩家是否看到過濾的聊天,而不是普通的聊天。
返回線上好友的辭典。
返回玩家在群組中的排名作為整數,介於 0 和 255 之間,其中 0 是非成員,255 是群組的所有者。
將玩家在群組中的角色返回為字串,或如果玩家不是群組的一部分,則為「訪客」。
檢查玩家是否是使用者的朋友,使用指定的 Player.UserId 。
檢查玩家是否是指定ID的群組成員。
生成一個虛擬人偶,使其配備了傳送過來的所有東西在HumanoidDescription中。
要求服務器傳送到指定位置附近的玩家。
活動
當玩家的角色生成或重生時,發射。
當完整的 Player.Character 外觀被插入時發生火災。
在玩家的角色被移除之前發射。
當玩家使用 Roblox 提供的聊天欄在遊戲中聊天時,發生火災。
此事件會在遊戲引擎將 player 分類為閒置後約兩分鐘發生。時間是自那一刻起過去的秒數。
當玩家的傳送狀態變更時發射。
屬性
AccountAge
帳戶年齡是一個 Player 描述玩家帳戶何時在天數內註冊的屬性。它使用 Player:SetAccountAge() 函數設置,不能被腳本存取。
此屬性對於條件地顯示新的 Roblox 玩家內容,例如教學,有用。
範例程式碼
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.
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
「自動跳躍啟用」屬性決定使用移動裝置的 是否會在碰到障礙物時自動跳躍。這可以在移動設備上使等級更易於導航。
當玩家加入遊戲時,StarterPlayer.AutoJumpEnabled值決定此屬性的初始狀態。然後,此屬性決定了 Humanoid.AutoJumpEnabled 在生成時的 Player.Character 屬性值。換言之,使用這三個屬性可以在每個角色、每個玩家和每場遊戲的基礎上設置自動跳躍行為。
範例程式碼
This code sample is meant for a TextButton. It allows the player to toggle the auto-jumping behavior while on a mobile device.
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
CameraMaxZoomDistance Player 屬性設置相機可以從預設相機到角色的最大距離,以磚格為單位。
換言之,它控制玩家的相機允許縮放的最大距離。
此屬性的預設值由 StarterPlayer.CameraMaxZoomDistance 設置。如果此值設為 Player.CameraMinZoomDistance 值低於,它將增加到相機縮放距離。
範例程式碼
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.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMaxZoomDistance = 50
player.CameraMinZoomDistance = 75
CameraMinZoomDistance
CameraMinZoonDistance Player 屬性設置相機可以從預設相機到角色的最小距離,以磚格為單位。
換言之,它控制玩家的相機允許放大的最小距離。
此屬性的預設值由 StarterPlayer.CameraMinZoomDistance 設置。如果此值設為高於 Player.CameraMaxZoomDistance 的值,它將被減少為相機最大縮放距離。
範例程式碼
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.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMaxZoomDistance = 50
player.CameraMinZoomDistance = 75
CameraMode
相機模式 屬性設置玩家的相機模式,默認為第三人稱。
第三人稱
在預設第三人稱模式(Enum.CameraMode.Classic)中,角色可以在相攝影機中看到。在此模式下,預設行為是:
- 玩家可以右鍵單擊並拖曳 (滑鼠)、點擊並拖曳 (手機)、使用次要搖桿 (遊戲手柄) 或按下左/右箭頭 (鍵盤) 來在他們的角色周圍旋轉相機。
- 當玩家移動角色時,它將面向相應的運動方向。
- 玩家可以自由縮放,甚至到全速縮放時變成第一人稱。
第一人稱
在第一人稱模式下(Enum.CameraMode.LockFirstPerson),玩家的相機縮放到最遠處。除非有可見的 GUI 與 GuiButton.Modal 屬性設置為 true ,否則移動滑鼠、在移動設備上拖動或使用游戏手柄上的第二個拇指將旋轉相機周圍角色。
範例程式碼
This example demonstrates how to change the character's CameraMode to first person using the LockFirstPerson value of the Enum.CameraMode enum.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMode = Enum.CameraMode.LockFirstPerson
CanLoadCharacterAppearance
CanLoadCharacterAppearance Player 屬性決定是否在玩家生成時載入角色的外觀。此特性的預設值由 StarterPlayer.LoadPlayerAppearance 設置。
如果 真實,角色將載入對應玩家的 Player.CharacterAppearanceId 的外觀。
如果 為 false,玩家將生成預設外觀 - 沒有任何帽子、襯衫、褲子等的灰色角色模型
在角色生成後設置屬性不會更改角色,您必須呼叫 Player:LoadCharacter() 來載入新外觀。
範例程式碼
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.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CanLoadCharacterAppearance = false
Character
角色 屬性包含一個指向包含Model、身體部位、腳本和其他對象的Humanoid的參考,用於模擬玩家在體驗中的人物形象。模型與 Workspace 相關,但可以移動。當 Players.CharacterAutoLoads 是 true 時,會自動載入,否則可以手動載入 Player:LoadCharacter() 。
初始此屬性是 nil ,當玩家的角色首次生成時設置。使用 Player.CharacterAdded 事件來偵測玩家角色正確載入時間,以及 Player.CharacterRemoving 事件來偵測角色即將淘汰時間。避免在此屬性上使用 Object:GetPropertyChangedSignal() 。
請注意,從 複製到玩家的 或 中的 或 等內容通常會在舊角色模型被替換之前執行,因此 可能會指向舊模型的 屬性。因此,在 LocalScript 下 StarterGui 或 StarterPack 中,建議在使用它之前確保 角色 的父不是 nil ,例如:
local Players = game:GetService("Players")local player = Players.LocalPlayerlocal character = player.Characterif not character or character.Parent == nil thencharacter = player.CharacterAdded:Wait()end
CharacterAppearanceId
此屬性決定使用玩家角色外觀的帳戶的用戶ID,用於玩家的 character 。預設情況下,此屬性是 Player.UserId ,使用玩家在 Roblox 網站上創建的虛擬人偶。
將此屬性變更為另一個帳戶的使用者ID會導致玩家重生到該帳號的外觀(帽子、襯衫、褲子等)。
遊戲也可以切換玩家角色是否在遊戲中載入,變更 StarterPlayer.LoadCharacterAppearance 屬性。
範例程式碼
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"!
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
定義如何預設攝影機腳本處理攝影機和攝影機主題之間的對象。由 StarterPlayer.DevCameraOcclusionMode 設置,不能為個別玩家變更。
預設值是 Zoom (0)。請參見 Enum.DevCameraOcclusionMode 獲得可用模式的列表。
DevComputerCameraMode
DevComputerCameraMode 屬性決定使用滑鼠和鍵盤裝置時玩家移動相機的方式。見 Enum.DevComputerCameraMovementMode 每個可用的相機控制模式的說明。此屬性無法使用 LocalScript 設置(必須在服務器上使用 Script)。
此特性的預設值由 StarterPlayer.DevComputerCameraMovementMode 決定。
此屬性名稱中的「電腦」一詞指的是非 TouchEnabled 、非 GamepadEnabled 裝置。
當設為 使用者選擇 時,玩家可以在 Roblox 遊戲設定中選擇任何控制模式 (除了 可腳本化 )。一般來說,允許玩家選擇控制模式以最大化輔助功能是一個好主意。
設置此屬性為 可執行 可創建自定控制計畫。
這個屬性不會影響使用觸摸啟用裝置的玩家。請參見 Player.DevTouchCameraMode 取而代之。
範例程式碼
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.
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
DevComputerMovementMode 屬性決定使用滑鼠和鍵盤裝置時玩家移動角色的方式。見 Enum.DevComputerMovementMode 每種可用的運動控制模式的說明。此屬性無法使用 LocalScript 設置(必須在服務器上使用 Script)。
此特性的預設值由 StarterPlayer.DevComputerMovementMode 決定。
此屬性名稱中的「電腦」一詞指的是非 TouchEnabled 裝置。
當設為 使用者選擇 時,玩家可以在 Roblox 遊戲設定中選擇任何控制模式 (除了 可腳本化 )。一般來說,允許玩家選擇控制模式以最大化輔助功能是一個好主意。
設置此屬性為 可執行 可創建自定控制計畫。
這個屬性不會影響使用觸摸啟用裝置的玩家。請參見 Player.DevTouchMovementMode 取而代之。
範例程式碼
Demonstrates how to set the movement mode for players on computers using the Player.DevComputerMovementMode property.
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
此屬性決定玩家是否能夠通過按下 Mouse 來切換 锁 。玩家可以在 Roblox 遊戲設定中停用滑鼠鎖定開關。預設值,此屬性設為 StarterPlayer.EnableMouseLockOption 的值。這可以在運行時使用 Script 設置服務器端。無法在客戶端設置。
啟用滑鼠鎖定時,玩家的鼠標會被鎖定在屏幕中央。移動鼠標將在玩家的 character 周圍繞著攝影機旋轉,角色將面向相同方向的 camera 。它也會抵消玩家角色右肩上的相機視圖。
請注意,與換擋鎖相關的 API 正在被棄用,因此建議使用 UserInputService.MouseBehavior 來鎖定鼠滑鼠。
範例程式碼
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.
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)
DevTouchCameraMode
DevTouchCameraMode 屬性決定玩家在使用 TouchEnabled 裝置時移動相機的方式。請參閱Enum.DevTouchCameraMovementMode每個可用的相機控制模式的說明。此屬性無法使用 LocalScript 設置(必須在服務器上使用 Script)。
此特性的預設值由 StarterPlayer.DevTouchCameraMovementMode 決定。
當設為 使用者選擇 時,玩家可以在 Roblox 遊戲設定中選擇任何控制模式 (除了 可腳本化 )。一般來說,允許玩家選擇控制模式以最大化輔助功能是一個好主意。
設置此屬性為 可執行 可創建自定控制計畫。
這個屬性不會影響那些沒有使用觸摸啟用裝置的玩家。請參見 Player.DevComputerCameraMovementMode 取而代之。
範例程式碼
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.
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
DevTouchMovementMode 屬性決定玩家在使用 TouchEnabled 裝置時移動角色的方式。見 Enum.DevTouchMovementMode 每種可用的運動控制模式的說明。此屬性無法使用 LocalScript 設置(必須在服務器上使用 Script)。
此特性的預設值由 StarterPlayer.DevTouchMovementMode 決定。
當設為 使用者選擇 時,玩家可以在 Roblox 遊戲設定中選擇任何控制模式 (除了 可腳本化 )。一般來說,允許玩家選擇控制模式以最大化輔助功能是一個好主意。
設置此屬性為 可執行 可創建自定控制計畫。
這個屬性不會影響那些沒有使用觸摸啟用裝置的玩家。請參見 Player.DevComputerMovementMode 取而代之。
範例程式碼
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.
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
DisplayName 是包含與 Player 對象相關的認證用戶顯示名稱的屬性 Player 。與使用者名稱不同,顯示名稱是玩家向他人顯示的非獨一名稱。如果 Roblox 使用者尚未選擇任何一個,屬性將與 Name 屬性相同。
注意:
- 因為顯示名稱不是唯一的,因此在單個實例中的兩名玩家可能擁有相同的名稱。如果您需要一個全球獨一無二的標識符來識別玩家,請使用 Player.UserId (它是靜態的) 或 Player.Name (它是目前的用戶名) 而不是使用。
- 顯示名稱可能包含字串中的Unicode字元。請參閱UTF-8了解有關如何與Unicode字元字串工作的更多信息。
FollowUserId
跟隨用戶ID是一個Player屬性,包含玩家跟隨到遊戲的用戶的Player.UserId。如果玩家沒有跟隨任何人進入遊戲,這個屬性將為 0。此屬性對於警告那些被另一名玩家跟隨到遊戲中的玩家有用。
您可以使用此使用者ID和 Players:GetNameFromUserIdAsync() 函數跟隨玩家的名稱。
範例程式碼
This code sample alerts players if a new player follows the local player into the game. Place this in a LocalScript in StarterPlayerScripts.
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
遊戲暫停 屬性表示玩家目前是否在啟用StreamingEnabled的暫停狀態。它設置在客戶端,但複製到服務伺服器。若要確定暫停狀態,您可以使用此屬性。
也見:
- Workspace.StreamingEnabled 控制是否啟用內容傳輸,以啟用內容傳輸
- Workspace.StreamingIntegrityMode 和 Enum.StreamingIntegrityMode 對於遊戲暫停的更多細節。
HealthDisplayDistance
生命顯示距離 Player 屬性設置此玩家將看到其他 Humanoid 生命條的距離以磚格為單位。如果設為 0,健康條不會顯示。此屬性預設值為 StarterPlayer.HealthDisplayDistance 。
如果人形的生命條可見,你可以使用 Humanoid.DisplayDistanceType 設置顯示類型。
範例程式碼
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.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.HealthDisplayDistance = 0
player.NameDisplayDistance = 0
LocaleId
本地ID Player 屬性顯示本地玩家為他們的 Roblox 帳號戶設置的本地ID。它持有帶有兩個字母代碼的字串(例如,"en-us")用於本地。
這可以用來確定遊戲玩家基礎的地理人口結構,也是將用於自動本地化(見 GuiBase2d.AutoLocalize)體驗內容的本地語言。此屬性可讓伺服器務器從玩家的本地存取。
也見 LocalizationService.RobloxLocaleId ,用於本地化內容的本地ID。當 Roblox 尚未內部支持本地玩家的設置本地時,這將是不同的值。
範例程式碼
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
local Players = game:GetService("Players")
local player = Players.LocalPlayer
print(player.LocaleId)
MembershipType
此屬性只能從中讀取以確定會員資格(不能設為另一種會員輸入)。它持有一個 Enum.MembershipType 枚列的帳號戶會員輸入。
範例程式碼
The following example checks whether a player has Premium membership.
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
名稱顯示距離 StarterPlayer 屬性設置此玩家將看到其他 Humanoid 名稱的距離,以厘米為單位。如果屬性設為 0,名稱將被隱藏。此屬性預設值為 StarterPlayer.NameDisplayDistance 。
如果人形的生命條可見,你可以使用 Humanoid.DisplayDistanceType 設置顯示類型。
範例程式碼
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.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.HealthDisplayDistance = 0
player.NameDisplayDistance = 0
Neutral
中立屬性決定玩家是否在特定團隊上。
範例程式碼
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.
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
ReplicationFocus
複製焦點 Player 屬性將部分聚焦在玩家周圍進行複製。通過網絡通信的不同 Roblox 系統(例如物理、傳輸等)會以不同速率複製,取決於對象與複製焦點的距離。
當此屬性為 nil 時,它會恢復到其預設行為,即將本地玩家的角色的 PrimaryPart 視為複製焦點。
此屬性應僅在服務器上設置 Script,而不是 LocalScript。請注意,此屬性不會更改或更新零件的網絡所有權。
範例程式碼
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.
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
如果設定,玩家將在指定的 SpawnLocation 重生。此屬性只能通過 Luau 設置,且必須包含指向有效的 SpawnLocation 的參考,該參考必須符合以下條件:
- 下屬於 Workspace
如果 RespawnLocation 未設為有效的 SpawnLocation 則會應用預設生成邏輯。有關此詳情,請參閱SpawnLocation。
重生位置的替代選擇
- 使用 PVInstance:PivotTo() 來手動移動 Player.Character 的自訂生成邏輯。
範例程式碼
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.
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
Team
團隊屬性是對 Team 服務中的 Teams 對象的參考。它決定玩家所屬的團隊;如果 Player 不在團隊上或有無效的 Player.TeamColor,此屬性是 nil 。當此特性設設定時,玩家已加入 Team 和 Team.PlayerAdded 事件發生在相關的團隊上。相同地, Team.PlayerRemoved 在屬性從特定 Team 中刪除時發生火災。
範例程式碼
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.
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".
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
團隊顏色屬性決定玩家與哪個團隊相關,根據該團隊的 Team.TeamColor 。變更此屬性將根據哪個團隊具有相同的 來變更 。如果沒有團隊對象擁有相關的團隊顏色,玩家將不會與團隊聯繫。
通常設定 Player.Team 到各自的 Team 而不使用此屬性會是更好的想法。設置此屬性會導致在許多腳本中重複相同的磚色值給特定團隊;這是你在遵守「不要重複自己」(DRY)原則時想要避免的情況。
範例程式碼
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.
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
UserId
使用者ID是一個 屬性,包含一個只讀的整數,可以唯一且一致地識別Roblox上的每個使用者帳戶。與玩家的 Instance.Name 不同,這個值永遠不會根據使用者現有的用使用者名稱變更,而是會永遠保持相同的帳號。
這個屬性在使用 GlobalDataStores 儲存/載入玩家資料時非常重要。使用玩家的使用者ID作為數據存儲鑰匙,每個玩家都有獨特的鍵。
範例程式碼
The below example would print the UserId of every user who entered a game.
local Players = game:GetService("Players")
local function onPlayerAdded(player)
print(player.UserId)
end
Players.PlayerAdded:Connect(onPlayerAdded)
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.
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.
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)
方法
ClearCharacterAppearance
清除角色外觀功能會從指定玩家的Accessory、Shirt、Pants、CharacterMesh和BodyColors中移除所有Player.Character。此外,它還移除玩家軀幹上的 T 恤Decal。角色的身體部位顏色和面部將保持不變。此方法如果玩家沒有角色,就不會做任何事情。
它不會移除t-shirts、頭部網格或面。
返回
範例程式碼
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
距離從角色 Player 函數返回角色頭和指定 Vector3 點之間的距離。如果玩家沒有 Player.Character,則返回 0。
這對於在遊戲中決定玩家與另一個對象或位置之間的距離很有用。
如果您想確定兩個非玩家實例或位置之間的距離,您可以使用以追蹤中內容:
local distance = (position1 - position2).Magnitude
參數
玩家距離到的位置正在被測量。
返回
玩家和位置之間的距離,以厘米為單位。
範例程式碼
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):
local Players = game:GetService("Players")
for _, player in pairs(Players:GetPlayers()) do
print(player:DistanceFromCharacter(Vector3.new(0, 0, 0)))
end
GetJoinData
返回包含描述玩家加入體驗的信息的辭典。辭典包含以下任一欄位:
<th>值類型</th><th>說明</th></tr></thead><tbody><tr><th>來源遊戲ID</th><td>數字</td><td>經驗中的 Class.DataModel.GameId 從玩家那裡傳送過來。只有當玩家傳送到當前體驗,並且伺服器呼叫傳送功能時,才會存在。</td></tr><tr><th>來源地點ID</th><td>數字</td><td>從<code>玩家</code>傳送到的地方的 <code>Class.DataModel.PlaceId</code>。只有當玩家傳送到當前位置並呼叫服務器呼叫傳送功能時,才會存在。</td></tr><tr><th>由玩家ID參考</th><td>數字</td><td>邀請現有玩家進入體驗的玩家的 <code>Class.Player.UserId</code>。使用此資料來識別來源並啟動獎勵邏輯。</td></tr><tr><th>會員</th><td>阵陣列</td><td>包含 <code>Class.Player.UserId</code> 用戶與 <code>玩家</code> 一起傳送的數字的數組。只有在玩家以群組的一部分進行傳送時才會出現。</td></tr><tr><th>傳送資料</th><td>變體</td><td>反映原始傳送中指定的 <code>傳送資料</code>。對於玩家傳送到的服務器之間分享資訊有用。只有指定 <code>teleportData</code> 時才會存在,並且伺服器呼叫傳送功能。</td></tr><tr><th>啟動資料</th><td>字串</td><td>一個簡單或 JSON 編碼的字串,包含指定在 <a href="../../../production/promotion/deeplinks.md">深鏈</a> URL 或 <code>Class.ExperienceInviteOptions.LaunchData</code> 中的啟動資料。</td></tr><tr><th>遊戲加入上下文</th> <td>字典</td><td>包含遊戲加入上下文相關資訊的辭典。它包含以下鑰匙:<ul><li><code>加入來源</code> : <code>Enum.JoinSource</code></li> <li><code>物品類型</code> : 可選 <code>Enum.AvatarItemType</code></li> <li><code>資產ID</code> : 可選 <code>string</code></li> <li><code>服裝ID</code> : 可選 <code>string</code></li> <li><code>資產類型</code> : 可選 <code>Enum.AssetType</code></li></ul></td></tr></tbody>
關鍵 |
---|
取得加入資料和傳送資料
如果伺服器啟動玩家的傳送,這個方法返回的辭典包括玩家的傳送數據。Player:GetJoinData() 方法只能用於在伺服器上取得傳送數據。要從客戶端取得資料,請使用 TeleportService:GetLocalPlayerTeleportData() 。
與 TeleportService:GetLocalPlayerTeleportData() 不同,Player:GetJoinData() 只提供符合以下安全標準的傳送資料:
- 保證在過去 48 小時內已由 Roblox 伺服器傳送。
- 保證使用此 Player 已傳送。
- SourcePlaceId 和 SourceGameId 保證是數據傳送的地方和宇宙。這表示您可以驗證傳送數據來自已批准的空間。
因為這些資料是由客戶端傳送的,因此仍然可能被濫用者濫用。玩家貨幣等敏感數據應透過像 記憶體儲存 這樣的安全解決方案傳送。
返回
包含 PlaceId 和 UserId 值的辭典(參見說明中的表)。
範例程式碼
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.
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.
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.
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.
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.
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
GetMouse Player 功能返回客戶端使用的 Mouse。玩家的滑鼠實例可用於跟蹤用戶滑鼠輸入,包括左右滑鼠按鈕點擊和移動以及位置。
服務提供額外的功能和事件來跟蹤用戶輸入 - 特別是對於不使用滑鼠的裝置。
注意:
- 此項目 必須 在 LocalScript 中使用,才能在線上 在線上按期運作。
- 在 2014 年 7 月的更新後,滑鼠標的圖示現在可以用此方法設置。
返回
範例程式碼
The below example will print:
Button 1 is down
whenever the Players.LocalPlayer left clicks.
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
取得網絡擊中 返回隔離網絡延遲的 Player 在秒內。「Ping」是指從客戶端傳送到伺服器的資料所需的時間,然後再返回的測量。它不涉及數據解碼或處理。
對於客戶端的 LocalScripts , 此功能只能在 Players.LocalPlayer 上呼叫。此功能在高網絡延遲場景中識別和解決發生的問題時有用。它也有助於遮蓋延遲,例如調整投射物動畫的速度。
返回
HasAppearanceLoaded
HasAppearanceLoaded Player 函數返回玩家的 Player.Character 是否已載入外觀。
玩家的外觀包括玩家的 Shirt , Pants 和 Accessories 等物品。
這有用於判斷玩家是否在首次加入遊戲後載入了外觀,可以使用 Players.PlayerAdded 事件進行跟蹤。
返回
一個是否指示玩家角色外觀已載入的 boolean 值。
範例程式碼
This example prints the result of Player:HasAppearanceLoaded() after a player joins the game until the 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
返回指示玩家驗證狀態的 boolean 值。當真實時,玩家會被驗證。驗證包括,但不限於非VOIP電話號碼或政府身份證驗證。
當執行 IsVerified 時,請注意確保實施不會誤堵所有未驗證的使用者。
請注意,此方法只能在後端伺服器上呼叫。呼叫它的客戶端結果導致錯誤。此外,此方法將永遠在 Studio 中返回 false 。
返回
一個是否指示玩家是否已驗證的 boolean 。
範例程式碼
The following example prints "true" if the player is verified.
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
Kick()允許體驗優雅地斷開客戶端並可選擇向斷開的用戶發送消息。這對於管理惡意使用者很有用。您只應允許您信任的特定使用者在其他使用者上啟動此方法。
在 Player 上呼叫此方法無參數會使用戶與服務器斷開並提供預設通知訊息。在 Player 上呼叫此方法,並將字串作為第一個參數,將提供的字串替換為預設訊息。
當從 LocalScript 使用此方法時,只有本地使用者的客戶端可以被踢出。
參數
在踢除使用者時顯示的訊息。
返回
Move
移動 Player 功能會導致玩家的角色在指定方向上走動,直到被停止或由玩家中斷 (使用他們的控制) 為止。
這對於在地圖上移動的 NPC Humanoids - 但並不受到實際玩家輸入的控制。
請注意,函數的第二個參數表示提供的 Vector3 是否應將玩家相對於世界坐標移動(false)或玩家的 Camera(真實)。
參數
玩家應該移動工具的向量 3 方向。
一個是否指示玩家應該相對於玩家的攝影機像機移動的 boolean。
返回
範例程式碼
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.
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)
SetAccountAge
SetAccountAge 功能設置玩家的 Player.AccountAge 天數。
它用於設置 Player 屬性,描述玩家帳戶何時在天數前註冊。
這不會設置帳帳號上玩家的年齡,但帳戶本身相對於第一次創建時的年齡。
參數
帳戶的日期(天)。
返回
範例程式碼
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.
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.
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
這個方法設置玩家是否看到過濾的聊天由 TextService:FilterStringAsync() 而不是普通聊天。
local Players = game:GetService("Players")local player = Players.LocalPlayerplayer:SetSuperSafeChat(true)
無論玩家是否啟用過濾聊天功能,所有聊天都應在播放給其他玩家或在玩家自己的屏幕上時被過濾TextService。TextService:FilterStringAsync() 返回可以根據訊息的預期使用情況進行篩選的 TextFilterResult 對象。
參數
一個是否指示玩家是否看到過濾的聊天的 boolean 值。
返回
GetFriendsOnline
此功能返回線上朋友的字典數組,受到 maxFriends 值限制。該功能使用 30 秒的緩存。
在返回的陣列中,某些欄位只存在於特定位置類型。例如, PlaceId 將不會在 LocationType 為0(手機網站)時出現。
<th>類型</th><th>說明</th></tr></thead><tbody><tr><td><b>訪客ID</b></td><td>數字</td><td>朋好友的 <code>Class.Player.UserId</code>。</td></tr><tr><td><b>使用者名稱</b></td><td>字串</td><td>朋好友的用戶名。</td></tr><tr><td><b>顯示名稱</b></td><td>字串</td><td>朋好友的 <code>Class.Player.DisplayName</code>。</td></tr><tr><td><b>最後在線</b></td><td>字串</td><td>當朋友上次在線上 在線時。</td></tr><tr><td><b>是否在線</b></td><td>boolean</td><td>如果朋友目前在線上 在線上。</td></tr><tr><td><b>最後位置</b></td><td>字串</td><td>朋好友當前位置的名稱。</td></tr><tr><td><b>地點ID</b></td><td>數字</td><td>朋好友最後位置的地點標識。</td></tr><tr><td><b>游戲ID</b></td><td>字串</td><td>朋好友最後位置的 <code>資料模型/工作ID</code>。</td></tr><tr><td><b>位置類型</b></td><td>數量</td><td>朋好友最後位置的位置類型:<table>0 移動網站 > 1 > 手機遊戲網頁 > 手機應用程式 > 2 > 桌面應用程式 > 桌面應用程式的位置類型: 手機應用程式的位置類型: 桌面應用程式的位置類型: 桌面應用程式的位置類型: 桌應用程式的位置類型:</table>手機應用程式的位置類型: 手機應用程式的位置類型: 位置類型: 手機應用程式的位置類型: 位置類型: 位置類型: 位置類型: 位置類型: 位置類型: 位置類型: 位置類型: 位置類型: 位置類型: 位置類型: 位置類: 位置類: 位置類: 位置類: 位置類: 位置類: 位置類: 位置類: 位置類: 位置類: 位置類: 位置類: 位置類: 位置類: 位置類: 位置類: 位置: 位置類: 位置類: 位置類: 位置類: 位置類: 位置類: 位置類: 位置: 位置: 位置類: 位置類: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位: 位: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位置: 位: 位: 位: 位: 位: 位: 位: 位: 位: 位: 位: 位: 位: 位: 位:</2: 位置: 位置: 位:</2:</2: 位:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:</2:2:</2:</2:2:</2:</2:</2:</2:</2:2:2:</2:</2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:2:</td></tr></tbody>
名稱 |
---|
參數
要傳回的在線好友最大數量。
返回
在線好友辭典(見上表)。
範例程式碼
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.
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
GetRankInGroup Player 功能返回玩家在群組中的排名作為一個整數,介於 0 和 255 之間,其中 0 是非成員,255 是群組的所有者。
使用此在 Script 中,而不是在 LocalScript 中,將無法獲得最新資訊。如果玩家在遊戲期間離開群組,GetRankInGroup仍會認為他們仍在該群組中,直到他們離開。但使用本地腳本時,這不會發生。
這是因為方法會儲存結果,因此多次呼叫同一玩家的 GetRankInGroup 方法,並使用相同的群組ID時,將與方法首次呼叫時的結果相同。緩存行為是基於每個對等的基礎上的:一個服務器不會與客戶分享相同的緩存。
參數
指定群組的 groupId 。
返回
玩家在群組中的排名。
範例程式碼
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.
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
GetRoleInGroup Player 功能返回玩家在群組中的角色作為字串,或 訪客 如果玩家不是群組的一部分。
使用此在 Script 中,而不是在 LocalScript 中,將無法獲得最新資訊。如果玩家在遊戲期間離開群組,GetRoleInGroup仍會認為他們仍在該群組中,直到他們離開為止。但使用本地腳本時,這不會發生。
這是因為方法會儲存結果,因此多次呼叫相同群組ID的GetRoleInGroup對同一玩家會產出與方法首次呼叫時相同的結果。緩存行為是基於每個對等的基礎上的:一個服務器不會與客戶分享相同的緩存。
參數
指定群組的 群組ID。
返回
玩家在指定的群組中的角色,或 訪客 如果玩家不是會成員 會員。
範例程式碼
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.
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
此功能向 Roblox 網站發送請求,問問玩家是否是另一個使用者的朋友,給予該使用者的 Player.UserId 。此功能會將結果緩存,因此多次呼叫相同玩家上的相同 Player.UserId 函數可能無法產生最新的結果。在 LocalScript 中使用時不會發生這種情況。
參數
指定玩家的 Player.UserId。
返回
一個是否指示玩家是否是指定使用者的朋友的 boolean 值。
範例程式碼
The below example would print whether or not a recently added player is friends with Gordonrox24.
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
IsInGroup Player 功能向 Roblox 網站發送請求,問題是玩家是否是該群組的成員,給予該群組的ID。
使用此在 Script 中,而不是在 LocalScript 中,將無法獲得最新資訊。如果玩家在遊戲期間離開群組,IsInGroup仍然會認為他們屬於該群組,直到他們離開。但使用本地腳本時,這不會發生。
這是因為方法會儲存結果,因此多次呼叫相同群組ID的同一玩家上的IsInGroup方法將與方法首次呼叫時相同的結果。緩存行為是基於每個對等的基礎上的:一個服務器不會與客戶分享相同的緩存。
參數
指定群組的 群組ID。
返回
一個是否指示玩家是否在指定的群組中。
範例程式碼
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.
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
LoadCharacter Player 功能創建一個新角色給玩家,移除舊角色。它也會清除玩家的 Backpack 和 PlayerGui 。
這在您想要在不殺死玩家的情況下重新載入角色時有用,例如當您想要在更換玩家的 Player.CharacterAppearance 後載入新角色外觀時。
注意: 功能與 Player:LoadCharacterBlocking() 相似,但要求會以異步方式處理,而不是同步方式。這表示其他任務在載入角色時仍能繼續進行,包括遊戲渲染和其他任務。此外,此功能可以在腳指令碼中使用,而 LoadCharacterBlocking 不行。
在為個別玩家呼叫 LoadCharacter 之後,不建議在該玩家的 Player.CharacterAppearanceLoaded 事件發生之後再次呼叫該玩家。
角色載入事件訂單
呼叫 Player:LoadCharacter() 使用 R15 虛擬人偶發射事件的順序如下(注意:R6 順序不同):
- 玩家.角色集
- 玩家.角色添加火焰
- 玩家.變更發生了值為「角色」的火焰
- 角色外觀初始化
- 玩家.角色外觀載入火
- 角色.父設為數據模型
- 角色模型建立和角色縮放
- 角色移動到生成地點
- 載入角色返回
返回
範例程式碼
This script turns off auto-loading and simulates character respawning.
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
此功能會生成一個虛擬人偶,因此它具備傳入的 HumanoidDescription 中的所有裝備。
呼叫 LoadCharacterWithHumanoidDescription 對個別玩家後,不建議再次呼叫該功能對同一玩家,直到該玩家的 Player.CharacterAppearanceLoaded 事件發生後。
也見:
- 人形描述系統,一篇文章,詳細解釋人形描述系統,並提供多個腳本示例
參數
包含身體部位/顏色、身體縮放、配件、服裝和動畫等特性的 HumanoidDescription 文件,將裝備到載入的角色。
返回
範例程式碼
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.
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
對於啟用實例 串流 的體驗,請求服務器傳送到 3D 世界的玩家區域 (零件和地形) 到指定的 X 、 Y 、 Z 位置。如果體驗知道玩家的 CFrame 將在不久的將來設置為指定位置,這會很有用。沒有提供這個呼叫的位置,玩家可能沒有為目的地傳送內容,導致傳輸暫停或其他不適當的行為。
這項呼叫的效果將是暫時的,並沒有保證指定位置附近會傳送什麼內容。客戶端記憶體限制和網路條件可能會影響客戶端上可用的內容。
使用小心
要求在區域周圍進行傳輸並不保證在請求完成時會有內容存在,因為傳輸會受到客戶端網絡帶寬、記憶限制和其他因素的影響。
參數
要求傳輸的世界位置。
對請邀請的可選時間限制,引擎在放棄請邀請之前,嘗試傳輸區域到 position 參數的最長時間。如果您未指定值,時間限制效果上是無限的。然而,如果客戶記憶體不足,引擎就會放棄所有的串流請求,即使它們仍然在時間限制內。
返回
活動
CharacterAdded
當玩家的角色生成 (或重生) 時, 角色添加 事件發生。此事件會在設置 Player.Character 為非 nil 值或呼叫 Player:LoadCharacter() 之後立即發生,這是在字元被父輩到 Workspace 之前。
這可以與 Player.CharacterRemoving 事件一起使用,該事件會在玩家的角色即將被移除之前發射,通常是死亡之後。因此,這兩個事件可能會在玩家死亡後重生到一個空間時發射多次。如果您想在玩家加入或離開遊戲時偵測,請使用 Players.PlayerAdded 和 Players.PlayerRemoving 事件。
請注意,當此事件發生時,Humanoid和其預設身體部位(頭、軀幹和肢體)將存在,但像Hats、Shirts和Pants等服裝項目可能需要幾秒鐘才能添加到角色。連接 Instance.ChildAdded 在添加的角色上偵測這些,或等待 Player.CharacterAppearanceLoaded 事件確保角色配備了所有設備。
參數
生成/重生的角色實例。
範例程式碼
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.
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.
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.
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
當插入完整的 Player.Character 外觀時,此事件會發生。
一個 Player.Character 通常會有一系列修改其外觀的對象,包括 Accoutrements , Shirts , Pants 和 CharacterMeshes 。當所有這些對象都被插入到 Player.Character 時,此事件將發生。
此事件只在伺服器上發生。
這個事件的一個使用是確保所有配件在摧毀它們之前都已載入。請參見下面的範例。
參數
範例程式碼
This code sample will wait for accessories to fully load, print out how many there are, and then destroy them all.
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
角色移除事件在玩家的角色被移除之前發生,例如當玩家重生時。
此事件可與 Player.CharacterAdded 事件一起使用,當玩家的角色生成或重生時發生。例個體、實例,如果您想每次玩家生成和死亡時打印一條訊息:
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)
此事件只關心 Character 的 Player 。如果您需要追蹤玩家何時加入/離開遊戲,請使用事件 Players.PlayerAdded 和 Players.PlayerRemoving 。
參數
正在移除的角色實例。
範例程式碼
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.
game.Players.PlayerAdded:Connect(function(player)
player.CharacterRemoving:Connect(function(character)
print(character.Name .. " has died.")
end)
end)
Chatted
聊天事件會在 Player 輸入訊息並按下 Roblox 提供的聊天欄時發生。這是使用預設聊天腳指令碼的一些 Luau 綁定來完成的。您可以使用 StarterGui:SetCoreGuiEnabled() 來防止玩家聊天,並停用聊天 Enum.CoreGuiType。
聊天指令
使用此事件和一些字串操作功能,例如 string.sub() 和 string.lower() , 即可創建聊天指令,甚至使用玩家名稱作為參數。通常,指令會以前缀,例如 heal PlayerName 。要檢查字串中的前缀,請在訊息上使用 string.sub() 來檢查訊息的子串:string.sub(message, 1, 6) == "/heal " (注意包含空空間)。然後,再次使用 string.sub() 來提取指令的剩餘部分:string.sub(message, 7) 將等於玩家名稱。檢查該玩家是否存在,如果存在,則執行指令的行動(在這個例子中,治療他們)。檢查代碼樣本以獲得聊天指令的例子。
過濾
使用此事件發射的訊息文字是 未過濾 。如果您以任何形式向其他玩家顯示聊天輸入,必須使用 Chat:FilterStringAsync() 過濾。創建自己的聊天系統時,請記住這一點;如果您的遊戲未能正確過濾聊天,它可能會受到管理行動的限制。
參數
範例程式碼
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.
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.
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".
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
此事件會在遊戲引擎將 player 分類為閒置後約兩分鐘發生。時間是自那一刻起過去的秒數。事件會繼續每 30 秒發射一次,直到玩家保持閒置狀態。
此事件只在客戶端腳本中發生,不是服務器腳本;使用 RemoteEvent 通知服務器空閒玩家。
Roblox 會自動切斷至少閒置 20 分鐘的玩家的連線,因此此事件對警告玩家他們即將被切斷很有用,或在那 20 分鐘之前切斷玩家的連線,或其他與鍵盤無關(AFK)功能。
要跟蹤自動切斷發生的頻率,請嘗試與 Players.PlayerRemoving 發生的事件相關。
參數
玩家閒置的時間(秒)。
範例程式碼
Prints how long a player has been idle for.
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
當玩家的傳送狀態變更時發射。這個事件有用於偵測是否傳送成功。
傳送狀態是什麼?
當使用 TeleportService 傳送請求時,Player 被傳送之前會經歷一系列階段。目前階段由 OnTeleport 提供的 Enum.TeleportState 值代表。請參見下面的實際範例。
參數
新的 Enum.TeleportState 的 Player .
如果使用了 TeleportService:TeleportToSpawnByName() 來傳送到目的地,傳送到的名稱。
範例程式碼
This example prints which stage of a teleport a player is at, as well as printing if the teleport was a failure.
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)