Players

非推奨を表示

*このコンテンツは、ベータ版のAI(人工知能)を使用して翻訳されており、エラーが含まれている可能性があります。このページを英語で表示するには、 こちら をクリックしてください。

作成できません
サービス

サービスには、現在接続されているクライアントに Roblox サーバーに接続するための オブジェクトが含まれています。また、場プレースの構成情報も含まれています。サーバーに接続していないプレイヤーに関する情報(キャラクターの外観、友達、アバターのサムネイルなど)を取得できます。

概要

プロパティ

  • 複製されていません
    スクリプト作成できません
    並列読み取り

    禁止 API を構成する 3 つの Players メソッド ( BanAsync() , UnbanAsync() , GetBanHistoryAsync() ) を有効化または無効化します。このプロパティはスクリプト化できず、Studio でのみ変更できます。

  • 読み取り専用
    複製されていません
    並列読み取り

    バブルチャットが有効かどうかを示します。Players:SetChatStyle() メソッドで設定されます。

  • 複製されていません
    並列読み取り

    characters が自動的に再スポーンするかどうかを示します。

  • 読み取り専用
    複製されていません
    並列読み取り

    クラシックチャットが有効かどうかを示します; Players:SetChatStyle() メソッドによって設定されます。

  • 読み取り専用
    複製されていません
    並列読み取り

    The Player が実行しているのは、LocalScript です。

  • 読み取り専用
    複製されていません
    並列読み取り

    サーバーに入れることができる最大プレイヤー数。

  • 読み取り専用
    複製されていません
    並列読み取り

    サーバーのプレイヤー数の推奨数。

  • 並列読み取り

    プレイヤーのキャラクターがリスポーンする時間量を制御します。

  • スクリプト作成できません
    並列読み取り

方法

  • Chat(message : string):()
    プラグインのセキュリティ

    ローカルプレイヤーが指定されたメッセージをチャットします。

  • 並列書き込み

    ゲーム内にある場合、Player を返し、指定された UserId を返します。

  • 返す の が指定されたインスタンスに一致するか、 が見つからない場合は、 。

  • GetPlayers():Instances
    並列書き込み

    現在接続されているすべての Player オブジェクトのテーブルを返します。

  • プラグインのセキュリティ

    バブルチャットとクラシックチャットが使用されているかどうかを設定し、チームチャットと Chat に何をすべきかを伝えます。

  • TeamChat(message : string):()
    プラグインのセキュリティ

    ローカルプレイヤーが指定されたメッセージをチャットし、同じチームのユーザーにのみ表示されます。

  • BanAsync(config : Dictionary):()
    イールド

    期間、理由、禁止が全宇宙に適用されるか現在のプレース所のみに適用されるかなど、禁止ユーザーをエクスペリエンスから排除するオプションを提供します。このメソッドは、Players.BanningEnabled プロパティによって有効化および無効化され、Studio で切り替えることができます。

  • パスされた HumanoidDescription に指定されたすべてを装備したキャラクターモデルを返し、rigType によって指定された R6 または R15 です。

  • パスされたユーザーのアバターに一致するように装備されたキャラクターモデル設定を返します。Returns a character Model set-up with everything equipped to match the avatar of the user specified by the passed in userId.

  • エクスペリエンスの宇宙内のユーザーの禁止と解除履歴を取得します。このメソッドは、Players.BanningEnabled プロパティによって有効化および無効化され、Studio で切り替えることができます。

  • 特定のユーザーのキャラクターの外観情報を返します。

  • イールド

    返す FriendPages オブジェクトには、指定されたプレイヤーの友達すべての情報が含まれています。

  • 指定された衣装のヒューマノイド説明を返し、衣装のパーツ/カラー/アニメーションなどで設定されます。

  • パスされたユーザーのアバターに指定されたものすべてを装備する HumanoidDescription を返します。

  • イールド

    指定された UserId のアカウントのユーザー名に関するクエリを Roblox ウェブサイトに送信します。

  • イールド

    指定されたユーザーユーザーネームを持つアカウントの userId に対して、Roblox ウェブサイトにクエリを送信します。

  • GetUserThumbnailAsync(userId : number,thumbnailType : Enum.ThumbnailType,thumbnailSize : Enum.ThumbnailSize):Tuple
    イールド

    サイズとタイプを指定して、プレイヤーのサムネイルのコンテンツ URLを返し、画像が使用できるかどうかを説明するボールーンを返します。

  • UnbanAsync(config : Dictionary):()
    イールド

    Players:BanAsync() またはユーザー制限オープンクラウド API から禁止されたプレイヤーを解除するこのメソッドは、Players.BanningEnabled プロパティによって有効化および無効化され、Studio で切り替えることができます。

イベント

プロパティ

BanningEnabled

複製されていません
スクリプト作成できません
並列読み取り

禁止 API を構成する 3 つの Players メソッド ( BanAsync() , UnbanAsync() , GetBanHistoryAsync() ) を有効化または無効化します。このプロパティはスクリプト化できず、Studio でのみ変更できます。

BubbleChat

読み取り専用
複製されていません
並列読み取り

このプロパティは、バブルチャットが有効かどうかを示します。Players:SetChatStyle() メソッドを使用して、Enum.ChatStyle 枚数を使用して設定されます。

このチャットモードが有効になっていると、ゲームはチャットユーザーインターフェイスを画面の左上隅に表示します。

他にも2つのチャットモードがあります、Players.ClassicChat と、クラシックとバブルチャットの両方が有効になっているチャットモードです。

CharacterAutoLoads

複製されていません
並列読み取り

このプロパティは、characters が自動的に再生するかどうかを示します。デフォルト値は true です。

このプロパティが無効になっている場合 (false)、プレイヤー は、プレイヤーがエクスペリエンスに参加するたびに 関数が呼び出されるまで、生成されません。

これは、プレイヤーに終わりのある生命がある経験で役立つ可能性があります、例えば、プレイヤーがゲームラウンドが終了するまでリスポーンしない競争ゲームです。

コードサンプル

This example demonstrates one possible usage of the Players.CharacterAutoLoads property.

The example below respawns all players in the game, if dead, once every 10 seconds. This means that players who die 1 second after all players respawn must wait 9 seconds until the script loads all Player.Character again.

First, this script removes a player's character when they die and the Humanoid.Died function fires. This is done so that the respawn loop that executes every 10 seconds reloads that player when it does not find the player's character in the Workspace.

To work as expected, this example should be run within a Script.

Player Respawn Timer

local Players = game:GetService("Players")
-- Set CharacterAutoLoads to false
Players.CharacterAutoLoads = false
-- Remove player's character from workspace on death
Players.PlayerAdded:Connect(function(player)
while true do
local char = player.CharacterAdded:Wait()
char.Humanoid.Died:Connect(function()
char:Destroy()
end)
end
end)
-- Respawn all dead players once every 10 seconds
while true do
local players = Players:GetChildren()
-- Check if each player is dead by checking if they have no character, if dead load that player's character
for _, player in pairs(players) do
if not workspace:FindFirstChild(player.Name) then
player:LoadCharacter()
end
end
-- Wait 10 seconds until next respawn check
task.wait(10)
end

ClassicChat

読み取り専用
複製されていません
並列読み取り

クラシックチャットが有効かどうかを示します。このプロパティは、Players:SetChatStyle() メソッドを使用して Enum.ChatStyle 枚数を設定します。

このチャットモードが有効になっていると、ゲームは送信者の頭上のバブルにチャットを表示します。

他にも2つのチャットモードがあります、Players.BubbleChat と、クラシックとバブルチャットの両方が有効になっているチャットモードです。

LocalPlayer

読み取り専用
複製されていません
並列読み取り

この読み込み専用プロパティは、クライアントがエクスペリエンスを実行している Player を参照します。

このプロパティは、クライアント上で実行するため、LocalScripts および ModuleScripts が必要なものにのみ定義されています。For the server, on which Script オブジェクトがコードを実行するサーバーの場合、このプロパティは nil です。

MaxPlayers

読み取り専用
複製されていません
並列読み取り

このプロパティは、サーバーに入れることができる最大プレイヤー数を決定します。このプロパティは、クリエイターダッシュボード または ゲーム設定 で特定の場プレースの設定を通じてのみ設定できます。

PreferredPlayers

読み取り専用
複製されていません
並列読み取り

このプロパティは、Roblox のマッチメイカーがサーバーを満たすプレイヤーの数を示します。この数は、エクスペリエンスがサポートする最大プレイヤー数(Players.MaxPlayers)より少ないでしょう。

RespawnTime

並列読み取り

このプロパティは、Players.CharacterAutoLoads が true になると、プレイヤーがリスポーンする時間、秒で制御します。デフォルトは 5.0秒です。

これは、経験の種類に基づいてリスポーンにかかる時間を変更したいが、個々のプレイヤーのスポーンを処理したくない場合に便利です。

このプロパティは、 内で設定できますが、Studio の Explorer ウィンドウで直接設定できるようになります。

UseStrafingAnimations

スクリプト作成できません
並列読み取り

方法

Chat

()
プラグインのセキュリティ

この機能は、ローカルプレイヤーに指定されたメッセージをチャットさせます。このアイテムは保護されているので、Script または LocalScript で使おうとするとエラーが発生します。

代わりに、カスタムチャットシステム、またはチャットへのアクセスが必要なシステムを作成するときは、Chat サービスのChat:Chat()機能を代わりに使用できます。

パラメータ

message: string

メッセージチャット。

既定値: ""

戻り値

()

コードサンプル

This example demonstrates that the Players:Chat() function executes without error if using the Command Bar or a Plugin (assuming the local player can chat freely) and errors if executed in a Script.

Players:Chat

-- Command bar
game:GetService("Players"):Chat("Hello, world!") --Results in 'Hello, world!' appearing in the Chat log under your Player's name.
-- Script
local Players = game:GetService("Players")
Players:Chat("Hello, world!") --Errors

GetPlayerByUserId

並列書き込み

この機能は、Player にあるすべての Players を検索し、Player.UserId が指定されたユーザーIDに一致するものを探します。そのようなプレイヤーが存在しない場合、単に nil を返します。次の機能と同等です:


local Players = game:GetService("Players")
local function getPlayerByUserId(userId)
for _, player in Players:GetPlayers() do
if player.UserId == userId then
return player
end
end
end

このメソッドは、MarketplaceService.ProcessReceipt を使用して開発者製品の購入者を見つけるのに便利で、購入者のユーザーIDを含むテーブルを提供し、プレイヤーオブジェクト自体へのリファレンスは含まれていません。ほとんどのゲームでは、製品を付与するにはプレイヤーへの参照が必要になります。

パラメータ

userId: number

指定されているプレイヤーの Player.UserId

既定値: ""

戻り値

コードサンプル

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:

  • Sets up the ProcessReceipt callback function to handle the purchase of two developer products for an experience.
  • Checks for and records purchases using a GlobalDataStore called PurchaseHistory.
  • Properly returns PurchaseGranted if the transaction completes successfully, or if the function detects that the purchase has already been granted using the PurchaseHistory data store.

After the receipt processing routine, it's possible that the purchase was granted but recording it as granted failed due to a data store error. This is one unavoidable scenario that leads to duplicate granting of the purchase, because processReceipt() will be called for the purchase again. You can mitigate this by keeping another in-memory record of purchases so that the same server will not grant the same purchase twice, but you'll need a session locking implementation around your data store to avoid the potential of duplicate grants across servers.

ProcessReceipt Callback

local MarketplaceService = game:GetService("MarketplaceService")
local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
-- Data store setup for tracking purchases that were successfully processed
local purchaseHistoryStore = DataStoreService:GetDataStore("PurchaseHistory")
local productIdByName = {
fullHeal = 123123,
gold100 = 456456,
}
-- A dictionary to look up the handler function to grant a purchase corresponding to a product ID
-- These functions return true if the purchase was granted successfully
-- These functions must never yield since they're called later within an UpdateAsync() callback
local grantPurchaseHandlerByProductId = {
[productIdByName.fullHeal] = function(_receipt, player)
local character = player.Character
local humanoid = character and character:FindFirstChild("Humanoid")
-- Ensure the player has a humanoid to heal
if not humanoid then
return false
end
-- Heal the player to full Health
humanoid.Health = humanoid.MaxHealth
-- Indicate a successful grant
return true
end,
[productIdByName.gold100] = function(_receipt, player)
local leaderstats = player:FindFirstChild("leaderstats")
local goldStat = leaderstats and leaderstats:FindFirstChild("Gold")
if not goldStat then
return false
end
-- Add 100 gold to the player's gold stat
goldStat.Value += 100
-- Indicate a successful grant
return true
end,
}
-- The core ProcessReceipt callback function
-- This implementation handles most failure scenarios but does not completely mitigate cross-server data failure scenarios
local function processReceipt(receiptInfo)
local success, result = pcall(
purchaseHistoryStore.UpdateAsync,
purchaseHistoryStore,
receiptInfo.PurchaseId,
function(isPurchased)
if isPurchased then
-- This purchase was already recorded as granted, so it must have previously been handled
-- Avoid calling the grant purchase handler here to prevent granting the purchase twice
-- While the value in the data store is already true, true is returned again so that the pcall result variable is also true
-- This will later be used to return PurchaseGranted from the receipt processor
return true
end
local player = Players:GetPlayerByUserId(receiptInfo.PlayerId)
if not player then
-- Avoids granting the purchase if the player is not in the server
-- When they rejoin, this receipt processor will be called again
return nil
end
local grantPurchaseHandler = grantPurchaseHandlerByProductId[receiptInfo.ProductId]
if not grantPurchaseHandler then
-- If there's no handler defined for this product ID, the purchase cannot be processed
-- This will never happen as long as a handler is set for every product ID sold in the experience
warn(`No purchase handler defined for product ID '{receiptInfo.ProductId}'`)
return nil
end
local handlerSucceeded, handlerResult = pcall(grantPurchaseHandler, receiptInfo, player)
if not handlerSucceeded then
local errorMessage = handlerResult
warn(
`Grant purchase handler errored while processing purchase from '{player.Name}' of product ID '{receiptInfo.ProductId}': {errorMessage}`
)
return nil
end
local didHandlerGrantPurchase = handlerResult == true
if not didHandlerGrantPurchase then
-- The handler did not grant the purchase, so record it as not granted
return nil
end
-- The purchase is now granted to the player, so record it as granted
-- This will later be used to return PurchaseGranted from the receipt processor
return true
end
)
if not success then
local errorMessage = result
warn(`Failed to process receipt due to data store error: {errorMessage}`)
return Enum.ProductPurchaseDecision.NotProcessedYet
end
local didGrantPurchase = result == true
return if didGrantPurchase
then Enum.ProductPurchaseDecision.PurchaseGranted
else Enum.ProductPurchaseDecision.NotProcessedYet
end
-- Set the callback; this can only be done once by one script on the server
MarketplaceService.ProcessReceipt = processReceipt

GetPlayerFromCharacter

この機能は、指定された または に関連する を返します。一致できない場合は、 または を返します。次の機能と同等です:


local function getPlayerFromCharacter(character)
for _, player in game:GetService("Players"):GetPlayers() do
if player.Character == character then
return player
end
end
end

このメソッドは、プレイヤーのキャラクターのいくつかのイベントが発動するときによく使用されます (例: 彼らの Humanoid dying )。そのようなイベントは、プレイヤーオブジェクトを直接参照しないかもしれませんが、このメソッドは簡単にアクセスできます。この機能の逆は、プレイヤーのキャラクターを取得すると説明できます。これを行うには、単にキャラクタープロパティにアクセスします。

パラメータ

character: Model

プレイヤーを取得したいキャラクターインスタンス。

既定値: ""

戻り値

コードサンプル

Players:GetPlayerFromCharacter

Players:GetPlayerFromCharacter

local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")
local PLAYER_NAME = "Nightriff"
local character = Workspace:FindFirstChild(PLAYER_NAME)
local player = Players:GetPlayerFromCharacter(character)
if player then
print(`Player {player.Name} ({player.UserId}) is in the game`)
else
print(`Player {PLAYER_NAME} is not in the game!`)
end

GetPlayers

Instances
並列書き込み

このメソッドは、現在接続されているすべての Player オブジェクトのテーブルを返します。それは同じ方法で機能します Instance:GetChildren() を除き、Player オブジェクトを Players の下でのみ返します。for ループと一緒に使用すると、ゲームのすべてのプレイヤーを反復するのに便利です。


local Players = game:GetService("Players")
for _, player in Players:GetPlayers() do
print(player.Name)
end

Players.PlayerAdded に接続するスクリプトは、よくゲームに接続するすべてのプレイヤーを処理しようとしています。このメソッドは、既に接続されたプレイヤーを反復するのに便利で、PlayerAdded を発射しないものです。この方法を使用すると、プレイヤーを見逃さないようになります!


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

戻り値

Instances

サーバー内のすべてのプレイヤーを含むテーブル。

コードサンプル

This code sample listens for players spawning and gives them Sparkles in their head. It does this by defining two functions, onPlayerSpawned and onPlayerAdded.

Give Sparkles to Everyone

local Players = game:GetService("Players")
local function onCharacterAdded(character)
-- Give them sparkles on their head if they don't have them yet
if not character:FindFirstChild("Sparkles") then
local sparkles = Instance.new("Sparkles")
sparkles.Parent = character:WaitForChild("Head")
end
end
local function onPlayerAdded(player)
-- Check if they already spawned in
if player.Character then
onCharacterAdded(player.Character)
end
-- Listen for the player (re)spawning
player.CharacterAdded:Connect(onCharacterAdded)
end
Players.PlayerAdded:Connect(onPlayerAdded)

SetChatStyle

()
プラグインのセキュリティ

この機能は、BubbleChat と ClassicChat が使用されているかどうかを設定し、チームチャットとチャットに Enum.ChatStyle 枚列を使用して何をすべきかを告知します。このアイテムは保護されているので、Script または LocalScript で使おうとするとエラーが発生します。

この機能は、ゲームによってチャットモードが設定されたとき内部で使用されます。

パラメータ

指定されたチャットスタイルが設設定するされました。

既定値: "Classic"

戻り値

()

コードサンプル

This example demonstrates that the Players:SetChatStyle() function executes without error if using the Command Bar or a Plugin and errors if executed in a LocalScript.

When executed in the Command Bar, this code sets the chat style to Classic using the Enum.ChatStyle enum.

Setting a Player's Chat Style

-- Command bar
game.Players:SetChatStyle(Enum.ChatStyle.Classic) -- Set's chat style to Classic
-- LocalScript
local Players = game:GetService("Players")
Players:SetChatStyle(Enum.ChatStyle.Classic) -- Errors

TeamChat

()
プラグインのセキュリティ

この機能は、Players.LocalPlayer チャットに指定されたメッセージを表示し、同じチームのユーザーにのみ表示されます。このアイテムは保護されているので、Script または LocalScript で使おうとするとエラーが発生します。

この機能は、Players.LocalPlayer がチームにメッセージを送信するときに内部で使用されます。

パラメータ

message: string

チャット中のメッセージ。

既定値: ""

戻り値

()

コードサンプル

This example demonstrates that the Players:TeamChat() function executes without error if using the Command Bar or a Plugin and errors if executed in a LocalScript.

When executed in the Command Bar, the function sends the specified message to all players on the same Team as the Players.LocalPlayer.

Sending Team Chat

-- Command bar
game.Players:TeamChat("Hello World") -- Sends a "Hello World" message to all players on the local player's team
-- LocalScript
local Players = game:GetService("Players")
Players:TeamChat("Hello World") -- Errors

BanAsync

()
イールド

Players:BanAsync() メソッドでは、エクスペリエンスのガイドラインに違反するユーザーを簡単に禁止できます。禁止期間を指定し、疑わしい代替アカウントに禁止を拡散させ、使用ガイドライン に従って禁止されたユーザーにメッセージを提異議申し立てできます。また、すべてのユーザーにアクセス可能な場所にあなたの経験ルールを投稿し、彼らが上訴できる方法を提供する必要があります。このメソッドは、Players.BanningEnabled プロパティによって有効化および無効化され、Studio で切り替えることができます。

禁止とメッセージ送信

禁止されたユーザーはすぐに排除され、エクスペリエンスに再参加することを禁止されます。彼らは、禁止時間とあなたの DisplayReason に残された時間を表示するエラーモードが表示されます。Roblox のバックエンドシステムは、指定した場プレースすべてのサーバーからプレイヤーを排除します。DisplayReason 最大長は 400 文字であり、テキストフィルターに対応します。受容可能なモーダルテキストに関する詳細は、禁止メッセージ を参照してください。

場所と宇宙

デフォルトでは、禁止はその宇宙内のどこかに拡張されます。この API が呼ばれている場所にのみ禁止を制限するには、ApplyToUniversefalse に構成します。しかし、ユーザーが宇宙の開始場所で禁止されると、ユニバーサル禁止が存在するかどうかにかかわらず、効果的にユーザーが宇宙全体から排除されることになります。

代替アカウント

ユーザはしばしば複数の異なるアカウント、別のアカウントまたは代替アカウントと呼ばれるものをプレイし、アカウント禁止を回避するために使用されます。禁止ユーザーを外すのを助けるために、この API のデフォルト動作は、禁止したソースアカウントから、疑われる代替アカウントのすべての禁止を拡散します。You can turn off ban propagations to alt accounts by configuring ExcludeAltAccounts to true .

禁止期間

すべての違反が同じではないので、すべての禁止が同じ長さである必要はありません。この API では、Duration フィールドで、禁アカウント停止の期間を秒単位で設定できます。永久禁アカウント停止を指定するには、フィールドを -1 に設定します。また、Players:GetBanHistoryAsync() を使用してクエリできるユーザーの禁止履歴に基づいて、禁止期間を動的に設定したい場合もあります。たとえば、禁止数、以前の禁止の期間、またはビルドロジックを保存したノート PrivateReason の下で保存されたメモの長さ (最大 1000 文字であり、テキストがフィルタリングされていません) を考慮したいかもしれません。PrivateReason ノートは決してクライアントと共有されず、攻撃者から安全と考えられます。

エラーと制限付き

このメソッドは、制限され、失敗する可能性のあるバックエンドサービスへの HTTP 呼び出しを発動します。この API を 1つ以上の UserId で呼んでいる場合、このメソッドは、それぞれのIDに対して HTTP 呼び出しを行おうとします。その後、すべてのエラーメッセージを集計し、コンマで区切られたリストとして結合します。たとえば、このメソッドが 5 ユーザーに呼び出され、 UserIds 2 と 4 を持つユーザーのリクエストが失敗した場合、次のエラーメッセージが表示されます:

HTTP failure for UserId 2: Timedout, HTTP 504 (Service unavailable) failure for UserId 4: Service exception

メッセージは常に failure for UserId {} を含むことになりますが、HTTP エラーの場合です。

クライアント側要件

ユーザーを禁止するリスクにより、このメソッドはバックエンドエクスペリエンスサーバー (クライアント側の呼び出しでエラーが発生する) でのみ呼び出されます。この API を Studi作品 で、共同作業 中、または チームテスト でテストできますが、生産には禁止が適用されません。

この API は ユーザー制限オープンクラウド API を使用します。これらの API を使用して、サードパーティのアプリケーションで禁止を管理できます。

パラメータ

config: Dictionary
  • UserIds (必須; 配列) — 禁止されるプレイヤーの UserIds の配列。最大サイズは 50 です。

  • ApplyToUniverse (オプション; ブール) — 禁止がエクスペリエンス宇宙内のすべての場所に拡散するかどうか。デフォルトは true です。

  • Duration (必須; 整数) — アカウント停止止の期間、秒。永久禁止は -1 の値を持つべきです。0 および他のすべてのネガティブ値は無効です。

  • DisplayReason (必須; 文字列) — ユーザーがエクスペリエンスに参加しようとして失敗したときに表示されるメッセージ。最大ストリング長は 400 です。

  • PrivateReason (必須; 文字列) — ユーザーの禁止履歴をクエリーすると返される内部メッセージ。最大文字列長は 1000 です。

  • ExcludeAltAccounts (オプション; ブール) — true のとき、Roblox は代替アカウントを禁止しようとしません。デフォルトは false です。

既定値: ""

戻り値

()

コードサンプル

The following example bans a user with a duration calculated from their ban history, scoped to the entire universe and all of the user's alternate accounts.

Banning Users

local Players = game:GetService("Players")
if shouldBeBanned(player) then
local banHistoryPages = Players:GetBanHistoryAsync(player.UserId)
local duration = getNextBanDuration(banHistoryPages) -- Creator-implemented logic
local config: BanConfigType = {
UserIds = { player.UserId },
Duration = duration,
DisplayReason = "You violated community guideline #5",
PrivateReason = "Put anything here that the user should not know but is helpful for your records",
ExcludeAltAccounts = false,
ApplyToUniverse = true,
}
local success, err = pcall(function()
return Players:BanAsync(config)
end)
print(success, err)
end

CreateHumanoidModelFromDescription

イールド

パスされた HumanoidDescription に指定されたすべてを装備したキャラクターモデルを返し、rigType によって指定された R6 または R15 です。

パラメータ

description: HumanoidDescription

返されたキャラクターの外観を指定します。

既定値: ""

返されたキャラクターが R6 か R15 かを指定します。

既定値: ""
assetTypeVerification: Enum.AssetTypeVerification

アセットタイプの検証では、この機能がモデルをロードするかどうかを判断します (カタログ資産以外の資産をロードしたい場合は、常にに設定する必要があります)。

既定値: "Default"

戻り値

ヒューマノイドキャラクタモデル。

コードサンプル

This code sample creates a Humanoid Model from the passed in HumanoidDescription and parents the Model to the Workspace.

Create Humanoid Model From Description

game.Players:CreateHumanoidModelFromDescription(Instance.new("HumanoidDescription"), Enum.HumanoidRigType.R15).Parent =
game.Workspace

CreateHumanoidModelFromUserId

イールド

パスされたユーザーのアバターに一致するように装備されたキャラクターモデル設定を返します。Returns a character Model set-up with everything equipped to match the avatar of the user specified by the passed in userId.これには、そのキャラクターが現在 R6 か R15 かどうかが含まれます。

パラメータ

userId: number

Roblox ユーザーのユーザーID。(ユーザーID はユーザープロフィールの番号ですなど www.roblox.com/users/1/profile)

既定値: ""

戻り値

ヒューマノイドキャラクタモデル。

コードサンプル

This code sample creates a Humanoid Model to match the avatar of the passed in User ID, and parents the Model to the Workspace.

Create Humanoid Model From A User ID

game.Players:CreateHumanoidModelFromUserId(1).Parent = game.Workspace

GetBanHistoryAsync

イールド

エクスペリエンスの宇宙内のユーザーの禁止と解除履歴を取得します。このメソッドは、BanHistoryPages から継承される Pages インスタンスを返します。このメソッドは、Players.BanningEnabled プロパティによって有効化および無効化され、Studio で切り替えることができます。

この関数呼び出しは、プロダクションゲームサーバーでのみ成功し、クライアントデバイスまたは Studio では成功しません。

この API は ユーザー制限オープンクラウド API を使用します。これらの API を使用して、サードパーティのアプリケーションで禁止を管理できます。

パラメータ

userId: number
既定値: ""

戻り値

返回参照は BanHistoryPages を参照してください。

GetCharacterAppearanceInfoAsync

イールド

この機能は、Roblox ウェブサイトでプレイヤーのアバター (装ギアを無視) に関する情報を辞書の形式で返します。これは、このメソッドで説明されたアセットを実際にロードする GetCharacterAppearanceAsync と混同してはならない。InsertService:LoadAsset() を使用して、プレイヤーのアバターで使用されるアセットをロードできます。返された辞書の構造は次のとおりです:


<th>種類</th>
<th>説明</th>
</tr>
</thead>
<tr>
<td><code>アセット</code></td>
<td>テーブル (下を参照)</td>
<td>装備されたアセット (帽子、体部など) を説明する</td>
</tr>
<tr>
<td><code>ボディカラー</code></td>
<td>テーブル (下を参照)</td>
<td>各肢の BrickColor 値を説明する</td>
</tr>
<tr>
<td><code>bodyColor3s</code></td>
<td>テーブル (下を参照)</td>
<td>体色と完全に一致しない可能性のある各肢の Color3 インスタンスを説明します</td>
</tr>
<tr>
<td><code>デフォルトのパンツが適用されました</code></td>
<td>bool</td>
<td>デフォルトのパンツが適用されるかどうかを説明します</td>
</tr>
<tr>
<td><code>デフォルトシャツ適用</code></td>
<td>bool</td>
<td>デフォルトのシャツが適用されるかどうかを説明します</td>
</tr>
<tr>
<td><code>エモート</code></td>
<td>テーブル (下を参照)</td>
<td>装備されたエモートアニメーションを説明する</td>
</tr>
<tr>
<td><code>プレイヤーアバタータイプ</code></td>
<td>文字列</td>
<td>「R15」または「R6」</td>
</tr>
<tr>
<td><code>スケール</code></td>
<td>テーブル (下を参照)</td>
<td>さまざまなボディスケーリング因子を説明する</td>
</tr>
名前
アセットサブテーブル

assets テーブルは、プレイヤーが現在装備しているアセットを説明する次のキーを含むテーブルの配列です:


<th>種類</th>
<th>説明</th>
</tr>
</thead>
<tr>
<td><code>id</code></td>
<td>番号</td>
<td>装備されたアセットのアセットID</td>
</tr>
<tr>
<td><code>アセットタイプ</code></td>
<td>テーブル</td>
<td>名前 と id フィールドを持つテーブル、それぞれが装備されたアセットの種類を説明 ("帽子""顔"など)</td>
</tr>
<tr>
<td><code>名前</code></td>
<td>文字列</td>
<td>装備されたアセットの名前</td>
</tr>
名前
スケールサブテーブル

scales テーブルには、それぞれ 1 つの Humanoid スケーリングプロパティに対応する次のキーがあります:bodyTypeheadheightproportiondepthwidth

ボディカラーサブテーブル

The bodyColors table has the following keys, each a number corresponding to a BrickColor ID number that can be used with BrickColor.new(id) : leftArmColorId , torsoColorId , rightArmColorId , headColorId , leftLegColorId , rightLegColorId .

パラメータ

userId: number

指定されたプレイヤーの * id

既定値: ""

戻り値

特定のユーザーのキャラクターの外観に関する情報を含む辞書。

コードサンプル

Sometimes it is best to see an example of the returned dictionary structure in pure Lua. Here is one such example of a player whose avatar uses a package and wears several hats. Can you guess who it is?

Example Return Character Appearance Dictionary

local result = {
playerAvatarType = "R15",
defaultPantsApplied = false,
defaultShirtApplied = false,
scales = {
bodyType = 0,
head = 1,
height = 1.05,
proportion = 0,
depth = 0.92,
width = 0.85,
},
bodyColors = {
leftArmColorId = 1030,
torsoColorId = 1001,
rightArmColorId = 1030,
headColorId = 1030,
leftLegColorId = 1001,
rightLegColorId = 1001,
},
assets = {
{
id = 1031492,
assetType = {
name = "Hat",
id = 8,
},
name = "Striped Hat",
},
{
id = 13062491,
assetType = {
name = "Face Accessory",
id = 42,
},
name = "Vision Française ",
},
{
id = 16598440,
assetType = {
name = "Neck Accessory",
id = 43,
},
name = "Red Bow Tie",
},
{
id = 28999228,
assetType = {
name = "Face",
id = 18,
},
name = "Joyous Surprise",
},
{
id = 86896488,
assetType = {
name = "Shirt",
id = 11,
},
name = "Expensive Red Tuxedo Jacket",
},
{
id = 86896502,
assetType = {
name = "Pants",
id = 12,
},
name = "Expensive Red Tuxedo Pants",
},
{
id = 376530220,
assetType = {
name = "Left Arm",
id = 29,
},
name = "ROBLOX Boy Left Arm",
},
{
id = 376531012,
assetType = {
name = "Right Arm",
id = 28,
},
name = "ROBLOX Boy Right Arm",
},
{
id = 376531300,
assetType = {
name = "Left Leg",
id = 30,
},
name = "ROBLOX Boy Left Leg",
},
{
id = 376531703,
assetType = {
name = "Right Leg",
id = 31,
},
name = "ROBLOX Boy Right Leg",
},
{
id = 376532000,
assetType = {
name = "Torso",
id = 27,
},
name = "ROBLOX Boy Torso",
},
},
}
print(result)

GetFriendsAsync

イールド

GetFriends Players 関数は、指定されたユーザーの友達の情報を含む FriendPages オブジェクトを返します。FriendPages オブジェクト内のアイテムは、次のフィールドを持つテーブルです:


<th>種類</th>
<th>説明</th>
</tr>
</thead>
<tr>
<td>Id</td>
<td>int64</td>
<td>友達のユーザーID</td>
</tr>
<tr>
<td>ユーザー名</td>
<td>文字列</td>
<td>友達のユーザー名</td>
</tr>
<tr>
<td>表示名称</td>
<td>文字列</td>
<td>友達の <code>Class.Player.DisplayName|display name</code> 。</td>
</tr>
名前

コードサンプルを見て、すべてのプレイヤーの友達を反復する簡単な方法を見つけましょう。

パラメータ

userId: number

指定されたプレイヤーのユーザーID。

既定値: ""

戻り値

コードサンプル

This code sample loads the Player.UserId of the player whose username is provided at the top of the script by using Players:GetUserIdFromNameAsync(). Then, it gets a FriendPages object by calling Players:GetFriendsAsync() and iterates over each entry using the iterPageItems function. The username of each friend is stored in a table, then printed at the end.

Print Roblox Friends

local Players = game:GetService("Players")
local USERNAME = "Cozecant"
local function iterPageItems(pages)
return coroutine.wrap(function()
local pagenum = 1
while true do
for _, item in ipairs(pages:GetCurrentPage()) do
coroutine.yield(item, pagenum)
end
if pages.IsFinished then
break
end
pages:AdvanceToNextPageAsync()
pagenum = pagenum + 1
end
end)
end
-- First, get the user ID of the player
local userId = Players:GetUserIdFromNameAsync(USERNAME)
-- Then, get a FriendPages object for their friends
local friendPages = Players:GetFriendsAsync(userId)
-- Iterate over the items in the pages. For FriendPages, these
-- are tables of information about the friend, including Username.
-- Collect each username in a table
local usernames = {}
for item, _pageNo in iterPageItems(friendPages) do
table.insert(usernames, item.Username)
end
print("Friends of " .. USERNAME .. ": " .. table.concat(usernames, ", "))

GetHumanoidDescriptionFromOutfitId

イールド

指定された衣装IDに対してヒューマノイドの説明を返し、衣装のパーツ/カラー/アニメーションなどで設定されます。衣装はユーザーによって作成されたもの、または Roblox によって作成されたバンドルの衣装であることができます。

パラメータ

outfitId: number

HumanoidDescription が検索される衣装の ID。

既定値: ""

戻り値

パスされた outfitId の仕様で初期化されたヒューマノイドの説明。

コードサンプル

Shows how to get the HumanoidDescription for bundle 799 (Fishman).

Get HumanoidDescription From Outfit ID

local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")
local function getOutfitId(bundleId)
if bundleId <= 0 then
return
end
local info = game.AssetService:GetBundleDetailsAsync(bundleId)
if not info then
return
end
for _, item in pairs(info.Items) do
if item.Type == "UserOutfit" then
return item.Id
end
end
return nil
end
local function getHumanoidDescriptionBundle(bundleId)
local itemId = getOutfitId(bundleId)
if itemId and itemId > 0 then
return Players:GetHumanoidDescriptionFromOutfitId(itemId)
end
return nil
end
local humanoidDescription = getHumanoidDescriptionBundle(799)
local humanoidModel = Players:CreateHumanoidModelFromDescription(humanoidDescription, Enum.HumanoidRigType.R15)
humanoidModel.Parent = Workspace

GetHumanoidDescriptionFromUserId

イールド

パスされたユーザーのアバターに指定されたものすべてを装備する HumanoidDescription を返します。スケールとボディカラーも含まれます。

パラメータ

userId: number

Roblox ユーザーのユーザーID。(ユーザーID はユーザープロフィールの番号ですなど www.roblox.com/users/1/profile)

既定値: ""

戻り値

ユーザーのアバター仕様で初期化されたヒューマノイドの説明。

コードサンプル

This code sample shows how to use GetHumanoidDescriptionFromUserId() to create a Humanoid Model.

Get HumanoidDescription From User ID

game.Players:CreateHumanoidModelFromDescription(
game.Players:GetHumanoidDescriptionFromUserId(1),
Enum.HumanoidRigType.R15
).Parent =
game.Workspace

GetNameFromUserIdAsync

イールド

GetNameFromUserIdAsync Players 関数は、指定された UserId のアカウントのユーザー名が何であるかを尋ねる Roblox ウェブサイトへのクエリを送信します。

このメソッドは、指定されたユーザーIDでアカウントが存在しない場合にエラーが発生します。そのようなアカウントが存在するかどうか確信できない場合は、この関数に対する呼び出しを pcall() で包むことをお勧めします。さらに、結果を手動でキャッシュして、同じユーザーID で将来の呼び出しを高速に行うこともできます。コードサンプルを見て、詳しく学ぶ。

パラメータ

userId: number

指定されているプレイヤーの Player.UserId

既定値: ""

戻り値

指定された Player.UserId を持つユーザーの名前。

コードサンプル

This code sample demonstrates using the Players:GetNameFromUserIdAsync() method to get a user's Player.Name from their Player.UserId.

Get Name from UserId

local Players = game:GetService("Players")
-- Example Data:
-- UserId: 118271 Name: "RobloxRulez"
-- UserId: 131963979 Name: "docsRule"
local nameOne = Players:GetNameFromUserIdAsync(118271)
local nameTwo = Players:GetNameFromUserIdAsync(131963979)
print(nameOne, nameTwo)
-- prints: "RobloxRulez docsRule"

This code sample demonstrates using the Players:GetNameFromUserIdAsync() method to get a user's Player.Name from their Player.UserId. Because GetNameFromUserIdAsync() yields, you can avoid calling it for the same Name using a table to store each UserId:Name pair found, called a cache. pcall() is used to catch the failure in case the Name doesn't exist.

Get Name from UserId using a cache

local Players = game:GetService("Players")
-- Create a table called 'cache' to store each 'Name' as they are found.
-- If we lookup a 'Name' using the same 'UserId', the 'Name' will come
-- from cache (fast) instead of GetNameFromUserIdAsync() (yields).
local cache = {}
function getNameFromUserId(userId)
-- First, check if the cache contains 'userId'
local nameFromCache = cache[userId]
if nameFromCache then
-- if a value was stored in the cache at key 'userId', then this 'nameFromCache'
-- is the correct Name and we can return it.
return nameFromCache
end
-- If here, 'userId' was not previously looked up and does not exist in the
-- cache. Now we need to use GetNameFromUserIdAsync() to look up the name
local name
local success, _ = pcall(function()
name = Players:GetNameFromUserIdAsync(userId)
end)
if success then
-- if 'success' is true, GetNameFromUserIdAsync() successfully found the
-- name. Store this name in the cache using 'userId' as the key so we
-- never have to look this name up in the future. Then return name.
cache[userId] = name
return name
end
-- If here, 'success' was false, meaning GetNameFromUserIdAsync()
-- was unable to find the 'name' for the 'userId' provided. Warn the user
-- this happened and then return nothing, or nil.
warn("Unable to find Name for UserId:", userId)
return nil
end
-- Example Data:
-- UserId: 118271 Name: "RobloxRulez"
-- UserId: 131963979 Name: "docsRule"
-- The first time a UserId is used, GetNameFromUserIdAsync() will be called
local nameOne = getNameFromUserId(118271)
local nameTwo = getNameFromUserId(131963979)
-- Because 118271 was previously used, get its Name from the cache
local nameOneQuick = getNameFromUserId(118271)
print(nameOne, nameTwo, nameOneQuick)
-- prints: "RobloxRulez docsRule RobloxRulez"

GetUserIdFromNameAsync

イールド

この機能は、Roblox ウェブサイトにクエリを送信し、指定された Player.UserId 名のアカウントの Player が何であるかを尋ねます。

このメソッドは、指定されたユーザー名でアカウントが存在しない場合にエラーが発生します。そのようなアカウントが存在するかどうか確信できない場合は、この関数に対する呼び出しを pcall() で包むことをお勧めします。さらに、結果を手動でキャッシュして、同じユーザー名を使用して将来の呼び出しを迅速に行うこともできます。コードサンプルを見て、詳しく学ぶ。

パラメータ

userName: string

指定されたプレイヤーのユーザー名。

既定値: ""

戻り値

名前が指定されたユーザーの Player.UserId

コードサンプル

This code sample demonstrates using the Players:GetUserIdFromNameAsync() method to get a user's Player.UserId from their Player.Name.

Get UserId from Name

local Players = game:GetService("Players")
-- Example Data:
-- UserId: 118271 Name: "RobloxRulez"
-- UserId: 131963979 Name: "docsRule"
local userIdOne = Players:GetUserIdFromNameAsync("RobloxRulez")
local userIdTwo = Players:GetUserIdFromNameAsync("docsRule")
print(userIdOne, userIdTwo)
-- prints: "118271 131963979"

This code sample demonstrates using the Players:GetUserIdFromNameAsync() method to get a user's Player.UserId from their Player.Name. Because GetUserIdFromNameAsync() yields, you can avoid calling it for the same UserId using a table to store each Name:UserId pair found, called a cache. pcall() is used to catch the failure in case the UserId doesn't exist.

Get UserId from Name using a cache

local Players = game:GetService("Players")
-- Create a table called 'cache' to store each 'UserId' as they are found.
-- If we lookup a 'UserId' using the same 'Name', the 'UserId' will come
-- from cache (fast) instead of GetUserIdFromNameAsync() (yields).
local cache = {}
function getUserIdFromName(name)
-- First, check if the cache contains 'name'
local userIdFromCache = cache[name]
if userIdFromCache then
-- if a value was stored in the cache at key 'name', then this 'userIdFromCache'
-- is the correct UserId and we can return it.
return userIdFromCache
end
-- If here, 'name' was not previously looked up and does not exist in the
-- cache. Now we need to use GetUserIdFromNameAsync() to look up the userId
local userId
local success, _ = pcall(function()
userId = Players:GetUserIdFromNameAsync(name)
end)
if success then
-- if 'success' is true, GetUserIdFromNameAsync() successfully found the
-- userId. Store this userId in the cache using 'name' as the key so we
-- never have to look this userId up in the future. Then return userId.
cache[name] = userId
return userId
end
-- If here, 'success' was false, meaning GetUserIdFromNameAsync()
-- was unable to find the 'userId' for the 'name' provided. We can warn the
-- user this happened and then return nothing, or nil.
warn("Unable to find UserId for Name:", name)
return nil
end
-- Example Data:
-- UserId: 118271 Name: "RobloxRulez"
-- UserId: 131963979 Name: "docsRule"
-- The first time a Name is used, GetUserIdFromNameAsync() will be called
local userIdOne = getUserIdFromName("RobloxRulez")
local userIdTwo = getUserIdFromName("docsRule")
-- Because "RobloxRulez" was previously used, get its UserId from the cache
local userIdOneQuick = getUserIdFromName("RobloxRulez")
print(userIdOne, userIdTwo, userIdOneQuick)
-- prints: "118271 131963979 118271"

GetUserThumbnailAsync

イールド

この機能は、プレイヤーのアバターの画像のコンテンツ URLを返し、UserId 、希望の画像サイズを Enum.ThumbnailSize 枚数、および希望のタイプを Enum.ThumbnailType 枚数とします。また、画像が使用できるかどうかを説明するブールを返します。

ほとんどの場合、このメソッドは ImageLabel.Image または Decal.Texture を使用して、エクスペリエンスでユーザーアバター画像を表示するために使用されます。

パラメータ

userId: number

指定されているプレイヤーの Player.UserId

既定値: ""
thumbnailType: Enum.ThumbnailType

A Enum.ThumbnailType サムネイルの種類を説明する。

既定値: ""
thumbnailSize: Enum.ThumbnailSize

A Enum.ThumbnailSize サムネイルのサイズを指定する。

既定値: ""

戻り値

指定されたパラメータに基づいてユーザーサムネイルのコンテンツ URL と、画像が使用できるかどうかを説明する bool を含むトゥプル。

コードサンプル

This code sample displays the current player's thumbnail in a parent ImageLabel by using Players:GetUserThumbnailAsync() and setting the Image() property as well as its Size().

Display Player Thumbnail

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local PLACEHOLDER_IMAGE = "rbxassetid://0" -- replace with placeholder image
-- fetch the thumbnail
local userId = player.UserId
local thumbType = Enum.ThumbnailType.HeadShot
local thumbSize = Enum.ThumbnailSize.Size420x420
local content, isReady = Players:GetUserThumbnailAsync(userId, thumbType, thumbSize)
-- set the ImageLabel's content to the user thumbnail
local imageLabel = script.Parent
imageLabel.Image = (isReady and content) or PLACEHOLDER_IMAGE
imageLabel.Size = UDim2.new(0, 420, 0, 420)

UnbanAsync

()
イールド

プレイヤーを Players:BanAsync() または ユーザー制限オープンクラウド API から禁止解除します。このメソッドは、Players.BanningEnabled プロパティによって有効化および無効化され、Studio で切り替えることができます。

Like Players:BanAsync() のように、このメソッドは、ユーザーを一括解除できる config 辞書を受け取ります。これにより、禁止解除されたユーザーと禁止解除された範囲が設定されます。

禁止の解除は、同じ ApplyToUniverse スコープの禁止にのみ効果があります。たとえば、 に設定された禁止を解除すると、 に設定された以前の禁止が無効にならないようになります。言い換えれば、宇宙レベルの禁止は場所レベルの禁アカウント停止を無効にはしません。反対も同じく真実です。

このメソッドは、制限されて失敗する可能性のある HTTP 呼び出しをバックエンドサービスに発行します。複数のユーザーID でこの API を呼び出している場合、このメソッドは、それぞれのユーザーID に対してこの HTTP 呼び出しを行おうとします。その後、すべてのエラーメッセージを集計し、コンマで区切られたリストとして結合します。たとえば、このメソッドが 5 個の UserIds で呼び出され、ユーザー 2 と 4 のリクエストが失敗した場合、次のエラーメッセージが表示されます: {1, 2, 3, 4, 5} メッセージには常に HTTP failure for UserId 2: Timedout, HTTP 504 (Service unavailable) failure for UserId 4: Service exception. が含まれます。HTTP エラーの場合は、failure for UserId {} も含まれます。有効なユーザーIDと無効なユーザーIDの両方を渡した場合は、定義されていない動作です、すなわちネットワークリクエストのすべての入力が有効に検証される前に、一部のリクエストが成功する可能性があるため、正の数字ではない UserId

ユーザーを禁止するリスクにより、このメソッドはバックエンドゲームサーバーでのみ呼び出される可能性があります。クライアント側の呼び出しはエラーになります。Studio、チーム作成、チームテストでこの API をテストできますが、禁止は生産には適用されません。この関数呼び出しは、プロダクションゲームサーバーでの禁止リクエストのみを試み、スタジオテストではありません。しかし、すべての入力検証ステップは、Studio でも引き続き機能します。

この API は ユーザー制限オープンクラウド API を使用します。これらの API を使用して、サードパーティのアプリケーションで禁止を管理できます。

パラメータ

config: Dictionary

<th>種類</th>
<th>説明</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>ユーザーID</code></td>
<td>配列</td>
<td>ユーザーID がエクスペリエンスに強制的に含まれるようにする。最大サイズは <code>50</code> です。</td>
</tr>
<tr>
<td><code>アプリケーションToUniverse</code></td>
<td>ブールン値</td>
<td>この宇宙内のすべての場所に禁止解除を拡散します。</td>
</tr>
</tbody>
名前
既定値: ""

戻り値

()

コードサンプル

The following un-bans a user, as well as another unrelated account with UserId 789.

Unbanning Users

local Players = game:GetService("Players")
if shouldBeUnbanned(player) then
local config: UnbanConfigType = {
UserIds = { player.UserId, 789 },
ApplyToUniverse = false,
}
local success, err = pcall(function()
return Players:UnbanAsync(config)
end)
print(success, err)
end

イベント

PlayerAdded

このイベントは、プレイヤーがゲームに入ると発動します。これは、プレイヤーがゲームに参加するときにイベントを発動するのに使用され、例えばプレイヤーの保存済みデータをロードすることです。

これは、プレイヤーがゲームを終了するときに発動する Players.PlayerRemoving イベントと一緒に使用できます。たとえば、新しいプレイヤーがゲームに参加または退出するたびにメッセージを印刷したい場インスタンス:


local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
print(player.Name .. " joined the game!")
end)
Players.PlayerRemoving:Connect(function(player)
print(player.Name .. " left the game!")
end)

プレイヤーのキャラクターがゲームに追加または削除されたときを追跡したい、例えば、プレイヤーがリスポーンしたり死んだりするとき、Player.CharacterAdded および Player.CharacterRemoving 機能を使用できます。

このイベントは、 プレイ モードでは、プレイヤーが PlayerAdded に接続するスクリプトを実行する前に作成されるため、期待通りに機能しません。このケースと、プレイヤーがゲームに入った後にスクリプトが追加されるケースを処理するには、プレイヤーの入り口を処理するために呼び出すことができる onPlayerAdded() 関数を作成してください。

パラメータ

player: Player

ゲームに参加したプレイヤーのインスタンス。


コードサンプル

This example will print "A player has entered: " followed by the name of the player that enters/joins a game every time a player joins.

Players.PlayerAdded

local Players = game:GetService("Players")
local function onPlayerAdded(player)
print("A player has entered: " .. player.Name)
end
Players.PlayerAdded:Connect(onPlayerAdded)

PlayerMembershipChanged

このイベントは、ゲームサーバーがプレイヤーのメンバーシップが変更されたことを認識したときに発動します。ただし、サーバーはプレミアムモードが閉じられた後にのみメンバーシップをチェックし更新しようとします 。たとえば、ゲームをプレイ中にユーザーがプレミアムを購入するケースを考えると、プレミアムを購入するように依然として促す必要があります。こうすることで、ゲームサーバーがメンバーシップをアップグレードし、このイベントをトリガーするという状況を回避できます。

プレミアムについて詳しく学び、エンゲージメントベースの支払いシステムで体験を構築し、エンゲージメントベースの支払いシステムで収益化するには、エンゲージメントベースの支払い を参照してください。

参照してください:

パラメータ

player: Player

コードサンプル

The function in the code sample runs after the game server confirms a player's membership has changed. It demonstrates how you can grant players access to Premium benefits (or revoke them) when their membership status changes.

Handling Premium Membership Changes

local Players = game:GetService("Players")
local function grantPremiumBenefits(player)
-- Grant the player access to Premium-only areas, items, or anything you can imagine!
print("Giving", player, "premium benefits!")
end
local function playerAdded(player)
if player.MembershipType == Enum.MembershipType.Premium then
grantPremiumBenefits(player)
end
end
local function playerMembershipChanged(player)
print("Received event PlayerMembershipChanged. New membership = " .. tostring(player.MembershipType))
if player.MembershipType == Enum.MembershipType.Premium then
grantPremiumBenefits(player)
end
end
Players.PlayerAdded:Connect(playerAdded)
Players.PlayerMembershipChanged:Connect(playerMembershipChanged)

PlayerRemoving

プレイヤー削除イベントは、Player がゲームを終了する直前に発動します。このイベントは、ChildRemovedPlayers で行う前に発動し、Instance.DescendantRemoving とほぼ同じように動作します。実際の Player の削除前に発射するため、このイベントは GlobalDataStore を使用してプレイヤーデータを保存するのに便利です。

これは、プレイヤーがゲームに参加すると発動する Player.PlayerAdded イベントと一緒に使用できます。たとえば、新しいプレイヤーがゲームに参加または退出するたびにメッセージを印刷するには:


local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
print(player.Name .. " joined the game!")
end)
Players.PlayerRemoving:Connect(function(player)
print(player.Name .. " left the game!")
end)

プレイヤーのキャラクターがゲームに追加または削除されたときを追跡したい、例えば、プレイヤーがリスポーンしたり死んだりするとき、Player.CharacterAdded および Player.CharacterRemoving 機能を使用できます。

パラメータ

player: Player

ゲームを終了するプレイヤーのインスタンス。


コードサンプル

This code will print "A player has left: ", followed by the player's name, every time a player leaves:

Players.PlayerRemoving

local Players = game:GetService("Players")
local function onPlayerRemoving(player)
print("A player has left: " .. player.Name)
end
Players.PlayerRemoving:Connect(onPlayerRemoving)

UserSubscriptionStatusChanged

このイベントは、ゲームサーバーが特定のサブスクリプションのユーザーのステータスが変更されたことを認識したときに発動します。サーバーは、サブスクリプション購入モードが閉じられた後にのみ、ステータスをチェックして更新しようとします 。ゲームをプレイ中にユーザーがサブスクリプションを購入するケースを考慮するには、サブスクリプションを購入するように依然として促す必要があります;促しはユーザーにすでにサブスクリプションに登録されているというメッセージを表示し、モーダルを閉じた後、ゲームサーバーはサブスクリプションのステータスを更新し、このイベントをトリガーします。

サーバースクリプトのみがこのイベントを受信することに注意してください。

パラメータ

user: Player

サブスクリプションステータスが変更されたユーザー。

subscriptionId: string

ステータス変更のあるサブスクリプションの ID。