Player
*此內容是使用 AI(Beta 測試版)翻譯,可能含有錯誤。若要以英文檢視此頁面,請按一下這裡。
概要
屬性
方法
活動
CharacterAdded(character: Model):RBXScriptSignal |
CharacterAppearanceLoaded(character: Model):RBXScriptSignal |
CharacterRemoving(character: Model):RBXScriptSignal |
Chatted(message: string,recipient: Player):RBXScriptSignal |
Idled(time: number):RBXScriptSignal |
OnTeleport(teleportState: Enum.TeleportState,placeId: number,spawnName: string):RBXScriptSignal |
API 參考
屬性
Auto Jump Enabled
範例程式碼
自動跳躍切換
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local button = script.Parent
local function update()
-- 更新按鈕文字
if player.AutoJumpEnabled then
button.Text = "自動跳躍已開啟"
else
button.Text = "自動跳躍已關閉"
end
-- 如果玩家有角色,則在角色中反映該屬性
if player.Character then
local human = player.Character:FindFirstChild("Humanoid")
if human then
human.AutoJumpEnabled = player.AutoJumpEnabled
end
end
end
local function onActivated()
-- 切換自動跳躍
player.AutoJumpEnabled = not player.AutoJumpEnabled
-- 更新其他所有內容
update()
end
button.Activated:Connect(onActivated)
update()Camera Mode
範例程式碼
第一人稱遊玩
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMode = Enum.CameraMode.LockFirstPersonCharacter
範例程式碼
角色
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()
endCharacter Appearance
Data Complexity
Data Ready
Follow User Id
範例程式碼
跟隨提醒
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 = "你被 " .. newPlayer.Name .. " 跟隨到這個遊戲!"
task.delay(3, function()
if textLabel then
textLabel:Destroy()
end
end)
end
end
Players.PlayerAdded:Connect(onPlayerAdded)Has Roblox Subscription
範例程式碼
檢查 Roblox 訂閱狀態
local Players = game:GetService("Players")
local player = Players.LocalPlayer
if player.HasRobloxSubscription then
-- 授予訂閱者專屬內容或福利
endMembership Type
Party Id
範例程式碼
Player.PartyId
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
local partyId = player.PartyId
if partyId ~= "" then
print("玩家在派對中,ID 為: " .. partyId)
else
print("玩家不在派對中")
end
player:GetPropertyChangedSignal("PartyId"):Connect(function()
if player.PartyId ~= "" then
print("玩家加入派對,ID 為: " .. player.PartyId)
else
print("玩家離開派對")
end
end)
end)Respawn Location
範例程式碼
觸碰時更改重生點
local Players = game:GetService("Players")
local function addSpawn(spawnLocation)
-- 監聽重生位置被觸碰
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")
-- 確保角色不是死亡狀態
if humanoid and humanoid:GetState() ~= Enum.HumanoidStateType.Dead then
print("重生點已設置")
player.RespawnLocation = spawnLocation
end
end
end
end)
end
local firstSpawn
-- 在工作空間中查找重生位置
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
-- 監聽新玩家
Players.PlayerAdded:Connect(playerAdded)
-- 遍歷現有玩家
for _, player in pairs(Players:GetPlayers()) do
playerAdded(player)
endThird Party Text Chat Restriction Status
User
範例程式碼
使用者
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
local user = player.User
print("域使用者 ID:", user.Id)
print("域類型:", user.DomainType)
print("域 ID:", user.DomainId)
end)User Id
範例程式碼
Player.UserId
local Players = game:GetService("Players")
local function onPlayerAdded(player)
-- 列印玩家的 UserId
print(player.UserId)
end
Players.PlayerAdded:Connect(onPlayerAdded)數據存儲到排行榜
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
-- 無法檢索數據
warn(result)
end
leaderstats.Parent = player
end
Players.PlayerAdded:Connect(onPlayerAdded)user Id
方法
Clear Cached Avatar Appearance
Player: Clear Cached Avatar Appearance():()
返回
()
Clear Character Appearance
Player: Clear Character 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, "從角色中移除")
end
character.ChildRemoved:Connect(onChildRemoved)
player:ClearCharacterAppearance()
--> 身體顏色從角色中移除
--> 襯衫圖形從角色中移除
--> 襯衫從角色中移除
--> 褲子從角色中移除
--> 角色網格從角色中移除
--> 帽子從角色中移除
--> 襯衫從角色中移除Distance From Character
參數
返回
範例程式碼
測量玩家與位置之間的距離
local Players = game:GetService("Players")
for _, player in pairs(Players:GetPlayers()) do
print(player:DistanceFromCharacter(Vector3.new(0, 0, 0)))
end角色距離
local position1 = Vector3.new(0, 0, 0)
local position2 = Vector3.new(0, 10, 0)
local distance = (position1 - position2).Magnitude
print(distance) --> 10Get Camera State
Player: Get Camera State():CameraState
返回
CameraState
範例程式碼
獲取相機狀態
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local cameraState = player:GetCameraState()
print(cameraState.CFrame)
print(cameraState.FieldOfView)
print(cameraState.ViewportSize)Get Friends Online
Get Friends Online Async
參數
| 預設值:200 |
返回
範例程式碼
獲取在線連接的列表
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local success, result = pcall(player.GetFriendsOnlineAsync, player, 10)
if success then
for _, friend in pairs(result) do
print(friend.UserName)
end
else
warn("獲取在線玩家失敗: " .. result)
endGet Join 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
-- 檢查提供的來源是否有效
if source and table.find(ALLOWED_SOURCES, source) then
-- 更新數據存儲以追蹤來源的受歡迎程度
local success, result = pcall(analyticsStore.IncrementAsync, analyticsStore, source)
if success then
print(player.Name, "從", source, "加入 - 總計:", result)
else
warn("記錄加入來源失敗: " .. result)
end
end
end
Players.PlayerAdded:Connect(onPlayerAdded)推薦網址生成器
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 -- 避免遞歸屬性更新
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)使用表格作為啟動數據
local HttpService = game:GetService("HttpService")
local DATA_CHARACTER_LIMIT = 200
local function encodeTableAsLaunchData(data)
-- 將表格轉換為字符串
local jsonEncodedData = HttpService:JSONEncode(data)
if #jsonEncodedData <= DATA_CHARACTER_LIMIT then
-- 轉義潛在的無效字符,例如空格
local urlEncodedData = HttpService:UrlEncode(jsonEncodedData)
return true, urlEncodedData
else
-- 報告字符限制錯誤
return false, ("編碼的表格超過 %d 字符限制"):format(DATA_CHARACTER_LIMIT)
end
end
local sampleData = {
joinMessage = "你好!",
urlCreationDate = os.time(),
magicNumbers = {
534,
1337,
746733573,
},
}
local success, encodedData = encodeTableAsLaunchData(sampleData)
if success then
print(encodedData)
else
warn("編碼啟動數據失敗: " .. encodedData)
end解碼 JSON 啟動數據
local HttpService = game:GetService("HttpService")
local Players = game:GetService("Players")
local function onPlayerAdded(player)
local launchData = player:GetJoinData().LaunchData
if launchData then
-- 嘗試解碼數據
local success, result = pcall(HttpService.JSONDecode, HttpService, launchData)
if success then
print(player.Name, "以數據加入:", result)
else
-- 這可能是因為用戶干擾了 URL
warn("解析啟動數據失敗:" .. result)
end
end
end
Players.PlayerAdded:Connect(onPlayerAdded)伺服器傳送資料範例
local Players = game:GetService("Players")
local approvedPlaceIds = { 1 } -- 在這裡插入已批准的 PlaceIds
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()
-- 驗證這些資料是由已批准的地方發送的
if isPlaceIdApproved(joinData.SourcePlaceId) then
local teleportData = joinData.TeleportData
if teleportData then
local currentLevel = teleportData.currentLevel
print(player.Name .. " 在等級 " .. currentLevel)
end
end
end
Players.PlayerAdded:Connect(onPlayerAdded)Get Rank In Group
Get Rank In Group Async
Get Role In Group
Get Role In Group Async
Has Appearance 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)Is Best Friends With
Is Friends With
is Friends With
Is In Group
Is Verified
參數
| 預設值:Low |
返回
範例程式碼
使用 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)Load Boolean
load Boolean
Load Character
Load Character Appearance
Load Character Async
Player: Load Character Async():()
返回
()
範例程式碼
關閉自動加載並模擬角色重生
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:LoadCharacterAsync()
end
humanoid.Died:Connect(onDied)
end
player.CharacterAdded:Connect(onCharacterAdded)
player:LoadCharacterAsync()
end
Players.PlayerAdded:Connect(onPlayerAdded)Load Character With Avatar Rules Async
Player: Load Character With Avatar Rules Async(avatar Rules:Variant):()
參數
avatarRules:Variant |
返回
()
Load Character With Humanoid Description
Load Character With Humanoid Description Async
Player: Load Character With Humanoid Description Async(
):()
參數
| 預設值:Default |
返回
()
範例程式碼
使用 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:LoadCharacterWithHumanoidDescriptionAsync(humanoidDescription)
end
Players.PlayerAdded:Connect(onPlayerAdded)Load Instance
load Instance
Load Number
load Number
Load String
load String
Move
返回
()
範例程式碼
相對於玩家相機移動
local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
-- 等待玩家的角色和人類模型,這在調用 :Move() 之前必須存在
local character = localPlayer.Character or localPlayer.CharacterAdded:Wait()
character:WaitForChild("Humanoid")
-- 玩家將移動,直到他們距離相機的位置 50 個單位
localPlayer:Move(Vector3.new(0, 0, -50), true)Prompt Age Check
Player: Prompt Age Check():()
返回
()
Request Stream Around Async
Save Boolean
save Boolean
Save Instance
save Instance
Save Number
save Number
Save String
save String
Wait For Data Ready
wait For Data Ready
活動
Character Added
參數
範例程式碼
檢測玩家生成和消失
local Players = game:GetService("Players")
local function onCharacterAdded(character)
print(character.Name .. " 已生成")
end
local function onCharacterRemoving(character)
print(character.Name .. " 正在消失")
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(onCharacterAdded)
player.CharacterRemoving:Connect(onCharacterRemoving)
end
Players.PlayerAdded:Connect(onPlayerAdded)配件移除器
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)
-- 等待片刻再移除配件以避免
-- "Something unexpectedly set ___ parent to NULL" 警告
RunService.Stepped:Wait()
-- 檢查玩家角色中是否有任何現有的配件
for _, child in pairs(character:GetChildren()) do
destroyAccessory(child)
end
-- 帽子可能會在 CharacterAdded 觸發後不久被添加到角色中,
-- 因此我們使用 ChildAdded 來監聽這些
character.ChildAdded:Connect(destroyAccessory)
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(onCharacterAdded)
end
Players.PlayerAdded:Connect(onPlayerAdded)Character Appearance Loaded
參數
範例程式碼
加載後移除配件
local Players = game:GetService("Players")
local function onPlayerAddedAsync(player)
local connection = player.CharacterAppearanceLoaded:Connect(function(character)
-- 此時所有配件都已加載
local humanoid = character:FindFirstChildOfClass("Humanoid")
local numAccessories = #humanoid:GetAccessories()
print(("銷毀 %d 個配件給 %s"):format(numAccessories, player.Name))
humanoid:RemoveAccessories()
end)
-- 確保在玩家離開後斷開與玩家的連接
-- 以允許玩家被垃圾回收
player.AncestryChanged:Wait()
connection:Disconnect()
end
for _, player in Players:GetPlayers() do
task.spawn(onPlayerAddedAsync, player)
end
Players.PlayerAdded:Connect(onPlayerAddedAsync)Character Removing
參數
範例程式碼
檢測玩家生成和消失
local Players = game:GetService("Players")
local function onCharacterAdded(character)
print(character.Name .. " 已生成")
end
local function onCharacterRemoving(character)
print(character.Name .. " 正在消失")
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(onCharacterAdded)
player.CharacterRemoving:Connect(onCharacterRemoving)
end
Players.PlayerAdded:Connect(onPlayerAdded)Chatted
On Teleport
Player. On Teleport(
參數
範例程式碼
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("傳送開始 (" .. playerOnTeleport.Name .. ")")
elseif teleportState == Enum.TeleportState.WaitingForServer then
print("傳送等待伺服器 (" .. playerOnTeleport.Name .. ")")
elseif teleportState == Enum.TeleportState.InProgress then
print("傳送進行中 (" .. playerOnTeleport.Name .. ")")
elseif teleportState == Enum.TeleportState.Failed then
print("傳送失敗! (" .. playerOnTeleport.Name .. ")")
end
end)
end)