Players

Visualizza obsoleti

*Questo contenuto è tradotto usando AI (Beta) e potrebbe contenere errori. Per visualizzare questa pagina in inglese, clicca qui.

Non costruibile
Assistenza

Il servizio Players contiene oggetti Player per i client connessi attualmente a un ServerRoblox.Contiene anche informazioni sulla configurazione di un Posto.Può recuperare informazioni sui giocatori non connessi al Server, come le apparizioni dei personaggi, gli amici e le miniature degli avatar.

Sommario

Proprietà

Metodi

Eventi

Proprietà

BanningEnabled

Non Replicato
Non programmabile
Lettura Parallela

Abilita o disabilita i tre metodi Players ( BanAsync() , UnbanAsync() e GetBanHistoryAsync() ) che costituiscono l'API di divieto.Questa proprietà non è scriptabile e può essere modificata solo in Studio.

BubbleChat

Sola Lettura
Non Replicato
Lettura Parallela

Questa proprietà indica se la chat a bolle è abilitata o meno. Viene impostata con il metodo Players:SetChatStyle() utilizzando l'enumero Enum.ChatStyle.

Quando questa modalità di chat è abilitata, il gioco visualizza le chat nell'interfaccia utente di chat nell'angolo in alto a sinistra dello schermo.

Ci sono altri due modi di chat, Players.ClassicChat e un modo di chat in cui sono abilitati sia la chat classica che la chat a bolle.

CharacterAutoLoads

Non Replicato
Lettura Parallela

Questa proprietà indica se characters respawnerà automaticamente. Il valore predefinito è vero.

Se questa proprietà è disabilitata (false), il giocatore characters non apparirà fino a quando non verrà chiamata la funzione Player:LoadCharacter() per ogni Player, incluso quando i giocatori si uniscono all'esperienza.

Questo può essere utile in esperienze in cui i giocatori hanno vitefinite, come giochi competitivi in cui i giocatori non respawnino fino a quando una partita non finisce.

Campioni di codice

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

Sola Lettura
Non Replicato
Lettura Parallela

Indica se la chat classica è abilitata o meno. Questa proprietà è impostata dal metodo Players:SetChatStyle() utilizzando l'enumero Enum.ChatStyle.

Quando questa modalità di chat è abilitata, il gioco visualizza le chat in una bolla sopra la testa del mittente.

Ci sono altri due modi di chat, Players.BubbleChat e un modo di chat in cui sono abilitati sia la chat classica che la chat a bolle.

LocalPlayer

Sola Lettura
Non Replicato
Lettura Parallela

Questa proprietà read-only si riferisce al Player il cui client sta eseguendo l'esperienza.

Questa proprietà è definita solo per LocalScripts e ModuleScripts richiesta da loro, poiché viene eseguita sul client.Per il Server, su cui gli oggetti Script eseguono il loro codice, questa proprietà è nil .

MaxPlayers

Sola Lettura
Non Replicato
Lettura Parallela

Questa proprietà determina il numero massimo di giocatori che possono essere in un Server.Questa proprietà può essere impostata solo attraverso le impostazioni di un Postospecifico sulla Dashboard del creatore o attraverso le impostazioni di Gioco.

PreferredPlayers

Sola Lettura
Non Replicato
Lettura Parallela

Questa proprietà indica il numero di giocatori a cui il matchmaker di Roblox riempirà i server.Questo numero sarà inferiore al numero massimo di giocatori ( Players.MaxPlayers ) supportati dall'esperienza.

RespawnTime

Lettura Parallela

Questa proprietà controlla il tempo, in secondi, che ci vuole perché un giocatore riappare quando Players.CharacterAutoLoads è vero. Si presta a 5.0 secondi.

Questo è utile quando vuoi cambiare il tempo necessario per respawn in base al tipo della tua esperienza ma non vuoi gestire lo spawning dei giocatori individualmente.

Sebbene questa proprietà possa essere impostata all'interno di un Script , puoi impostarla più facilmente direttamente sull'oggetto Players in Studio nella finestra Explorer.

UseStrafingAnimations

Non programmabile
Lettura Parallela

Metodi

Chat

()
Sicurezza Plugin

Questa funzione fa chattare al giocatore locale il Messaggiodato.Poiché questo oggetto è protetto, tentare di utilizzarlo in un Script o LocalScript causerà un errore.

Invece, quando crei un sistema di chat personalizzato, o un sistema che ha bisogno di accedere alla chat, puoi usare la funzione Chat del servizio Chat:Chat() invece.

Parametri

message: string

Il messaggio chat.

Valore predefinito: ""

Restituzioni

()

Campioni di codice

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

Scrivi Parallelo

Questa funzione cerca ogni Player in Players per uno il cui Player.UserId corrisponde alla dato userId .Se un tale giocatore non esiste, restituisce nil .

Questo metodo è utile per trovare il compratore di un prodotto sviluppatore utilizzando MarketplaceService.ProcessReceipt che fornisce una tabella che include il compratore di UserId e non un riferimento all'oggetto Player stesso.La maggior parte delle esperienze richiederà un riferimento al giocatore per concedere prodotti.

Parametri

userId: number

Il Player.UserId del giocatore che viene specificato.

Valore predefinito: ""

Restituzioni

Campioni di codice

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

GetPlayerFromCharacter

Questa funzione restituisce il Player associato al dato Player.Character , o nil se non si può trovare.Equivale alla seguente funzione:


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

Questo metodo viene spesso utilizzato quando si attiva un evento nel personaggio del Giocatore(come il loro Class.Humanoid``Class.Humanoid.Died|dying ).Un evento del genere potrebbe non fare riferimento direttamente all'oggetto Player, ma questo metodo fornisce un Accessosemplice.L'inverso di questa funzione può essere descritto come ottenere il personaggio di un giocatore.Per fare ciò, accedi semplicemente alla ProprietàPersonaggio.

Parametri

character: Model

Un'istanza di personaggio da cui vuoi ottenere il giocatore.

Valore predefinito: ""

Restituzioni

Campioni di codice

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
Scrivi Parallelo

Questo metodo restituisce una tabella di tutti gli oggetti attualmente connessi Player .Funziona allo stesso modo Instance:GetChildren() sarebbe escluso che restituisce solo oggetti Player trovati sotto Players .Quando viene utilizzato con un ciclo for , è utile per itterare su tutti i giocatori in un Gioco.


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

Gli script che si connettono a Players.PlayerAdded sono spesso in cerca di elaborare ogni giocatore che si connette al Gioco.Questo metodo è utile per itterare su giocatori già connessi che non sparerebbero PlayerAdded .L'utilizzo di questo metodo garantisce che nessun giocatore venga perso!


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)

Restituzioni

Instances

Un tavolo che contiene tutti i giocatori nel Server.

Campioni di codice

Questo esempio di codice ascolta i giocatori che si generano e dà loro Scintille nella loro testa.Lo fa definendo due funzioni, onPlayerSpawned e onPlayerAdded.

Dai scintille a tutti

local Players = game:GetService("Players")
local function onCharacterAdded(character)
-- Dagli scintille sulla loro testa se non li hanno ancora
if not character:FindFirstChild("Sparkles") then
local sparkles = Instance.new("Sparkles")
sparkles.Parent = character:WaitForChild("Head")
end
end
local function onPlayerAdded(player)
-- Verifica se sono già stati generati in
if player.Character then
onCharacterAdded(player.Character)
end
-- Ascolta il giocatore (re)spawning
player.CharacterAdded:Connect(onCharacterAdded)
end
Players.PlayerAdded:Connect(onPlayerAdded)

SetChatStyle

()
Sicurezza Plugin

Questa funzione imposta se BubbleChat e ClassicChat sono in uso e dice a TeamChat e Chat cosa fare utilizzando l'enumero Enum.ChatStyle.Poiché questo oggetto è protetto, tentare di utilizzarlo in un Script o LocalScript causerà un errore.

Questa funzione viene utilizzata internamente quando la modalità chat è impostata dal Gioco.

Parametri

Lo stile di chat specificato viene Impostare.

Valore predefinito: "Classic"

Restituzioni

()

Campioni di codice

Questo esempio dimostra che la funzione Players:SetChatStyle() esegue senza errore se utilizza la barra dei comandi o un plugin e gli errori se eseguita in un LocalScript .

Quando viene eseguito nella barra dei comandi, questo codice imposta lo stile di chat a Classico utilizzando l'enumero Enum.ChatStyle.

Impostare lo stile di chat di un giocatore

-- Barra dei comandi
game.Players:SetChatStyle(Enum.ChatStyle.Classic) -- Imposta lo stile di chat a Classico
-- Script locale
local Players = game:GetService("Players")
Players:SetChatStyle(Enum.ChatStyle.Classic) -- Errors

TeamChat

()
Sicurezza Plugin

Questa funzione fa in modo che la chat Players.LocalPlayer riceva il Messaggiofornito, che sarà visibile solo dagli utenti della stessa team.Poiché questo oggetto è protetto, tentare di utilizzarlo in un Script o LocalScript causerà un errore.

Questa funzione viene utilizzata internamente quando il Players.LocalPlayer invia un messaggio al loro team.

Parametri

message: string

Il messaggio in chat.

Valore predefinito: ""

Restituzioni

()

Campioni di codice

Questo esempio dimostra che la funzione Players:TeamChat() esegue senza errore se utilizza la barra dei comandi o un plugin e gli errori se eseguita in un LocalScript .

Quando viene eseguita nella barra dei comandi, la funzione invia il messaggio specificato a tutti i giocatori sullo stesso Team come il Players.LocalPlayer.

Invio di chat di squadra

-- Barra dei comandi
game.Players:TeamChat("Hello World") -- Invia un messaggio "Hello World" a tutti i giocatori della squadra del giocatore locale
-- Script locale
local Players = game:GetService("Players")
Players:TeamChat("Hello World") -- Errors

BanAsync

()
Resa

Il metodo Players:BanAsync() ti consente di bannare facilmente gli utenti che violano le linee guida della tua esperienza.Puoi specificare la durata del divieto, abilitare il divieto a propagarsi a account alternativi sospetti e fornire un messaggio all'utente divietato in conformità alle linee guida sull'uso.Dovresti anche pubblicare le regole della tua esperienza in un luogo accessibile a tutti gli utenti e fornire un modo per loro di fare appello, appellare, ricorrere.Questo metodo è abilitato e disabilitato dalla ProprietàPlayers.BanningEnabled, che puoi attivare in Studio.

Ban e messaggi

Gli utenti vietati verranno immediatamente espulsi e impediti di ricongiungersi alle tue esperienze.Verranno presentati con un errore che mostra il tempo rimanente sul loro ban e il tuo DisplayReason .I sistemi backend di Roblox espelleranno i giocatori su tutti i server dalla Posto(i) che specifica.DisplayReason può avere una lunghezza massima di 400 caratteri e è soggetto a un Filtrodi testo.Per maggiori informazioni sul testo modale accettabile, vedi messaggi di divieto.

Posti e Universo

Per impostazione predefinita, i divieti si estendono a qualsiasi luogo all'interno di quell'universo.Per limitare il divieto solo al luogo da cui viene chiamata questa API, configura ApplyToUniverse a false .Tuttavia, se un utente viene bannato nel luogo di partenza dell'universo, effettivamente risulta nell'esclusione dell'utente dall'interezza dell'universo, indipendentemente dal fatto che sia in vigore un divieto universale o meno.

Conti alternativi

Gli utenti spesso giocano sotto più account diversi, noti come account alternativi o conti alt, che a volte vengono utilizzati per aggirare i divieti di account.Per aiutarti a mantenere gli utenti vietati fuori, il comportamento predefinito di questa API propagherà tutti i divieti dall'account di origine che hai vietato a uno qualsiasi dei loro presunti account alternativi.Puoi disattivare le propagazioni di divieto agli account alternativi configurando ExcludeAltAccounts a true .

Durata del ban

Non tutte le transgressioni sono uguali, quindi non tutti i divieti dovrebbero essere della stessa lunghezza.Questa API ti consente di configurare la durata del bandire, in secondi, con il campo Duration.Per specificare un bandirepermanente, imposta il campo a -1 .Potresti anche voler configurare dinamicamente la durata del ban in base alla storia del ban dell'utente, che puoi interrogare per utilizzare Players:GetBanHistoryAsync() .Ad esempio, potresti voler considerare il numero di divieti, la durata dei divieti precedenti o costruire la logica a partire dalle note che salvi sotto PrivateReason , che possono essere fino a 1000 caratteri e non sono filtrati dal testo.PrivateReason le note non vengono mai condivise con il client e possono essere considerate al sicuro dagli attaccanti.

Errori e Throttling

Questo metodo invoca una chiamata HTTP ai servizi backend che sono soggetti a throttling e possono fallire.Se stai chiamando questa API con più di un UserId, questo metodo cercherà di fare la chiamata HTTP per ciascun ID.Quindi aggregherà tutti i messaggi di errore e li unirà come una lista separata da virgola.Ad esempio, se questo metodo viene invocato per cinque utenti e le richieste per quelli con UserIds 2 e 4 falliscono, appare il seguente messaggio di errore:

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

Il messaggio includerà sempre failure for UserId {} se è un errore HTTP.

Requisito lato client

A causa dei rischi associati alla bannatura degli utenti, questo metodo può essere richiesto solo sul server dell'esperienza backend (le chiamate lato client daranno luogo a un errore).Puoi testare questa API in Studio, durante la Creazionicollaborativa, o in un test di squadra, ma i divieti non si applicheranno alla produzione.

Questa API utilizza la Restrizioni utente Open Cloud API. Potrai utilizzare queste API per gestire i tuoi divieti in applicazioni di terze parti.

Parametri

config: Dictionary
  • UserIds (richiesto; vettore) — Array di UserIds di giocatori da bannare. La dimensione massima è 50 .

  • ApplyToUniverse (opzionale; booleano) — Se il ban si diffonde in tutti i luoghi all'interno dell'universo dell'esperienza. Il predefinito è true .

  • Duration (richiesto; intero) — Durata del bandire, in secondi.I divieti permanenti dovrebbero avere un valore di -1 .0 e tutti gli altri valori negativi non sono validi.

  • DisplayReason (richiesto; Stringa) — Il messaggio che verrà visualizzato agli utenti quando tentano di unirsi e non riescono a un'esperienza.La lunghezza massima della stringa è 400 .

  • PrivateReason (richiesto; Stringa) — Messaggi interni che verranno restituiti quando si cerca la cronologia del ban dell'utente. La lunghezza massima della stringa è 1000 .

  • ExcludeAltAccounts (opzionale; booleano) — Quando true , Roblox non tenta di bandire gli account alternativi. Il predefinito è false .

Valore predefinito: ""

Restituzioni

()

Campioni di codice

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

Resa

Restituisce un modello di personaggio equipaggiato con tutto ciò che è specificato nella HumanoidDescription passata e è R6 o R15 come specificato dal rigType.

Parametri

description: HumanoidDescription

Specifica l'aspetto del personaggio restituito.

Valore predefinito: ""

Specifica se il personaggio restituito sarà R6 o R15.

Valore predefinito: ""
assetTypeVerification: Enum.AssetTypeVerification

La verifica del tipo di risorsa determina se questa funzione caricherà modelli o meno (Devi impostarla sempre a meno che non voglia caricare risorse non catalogate).

Valore predefinito: "Default"

Restituzioni

Un modello di personaggio umanoide.

Campioni di codice

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

Resa

Restituisce un set di configurazione del modello di personaggio con tutto ciò che è equipaggiato per corrispondere all'avatar dell'utente specificato dall'userId inserito.Questo include se quel personaggio è attualmente R6 o R15.

Parametri

userId: number

L'ID utente per un utente Roblox. (L'ID utente è il numero nel profilo dell'utente ad esempio www.roblox.com/users/1/profile).

Valore predefinito: ""

Restituzioni

Un modello di personaggio umanoide.

Campioni di codice

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

Resa

Recupera la cronologia del ban e del disban di qualsiasi utente all'interno dell'universo dell'esperienza.Questo metodo restituisce un'istanza BanHistoryPages che eredita da Pages.Questo metodo è abilitato e disabilitato dalla ProprietàPlayers.BanningEnabled, che puoi attivare in Studio.

Questa chiamata di funzione avrà successo solo sui server di gioco di produzione e non su dispositivi client o in Studio.

Questa API utilizza la Restrizioni utente Open Cloud API. Potrai utilizzare queste API per gestire i tuoi divieti in applicazioni di terze parti.

Parametri

userId: number
Valore predefinito: ""

Restituzioni

Vedi BanHistoryPages per il riferimento di restituzione.

GetCharacterAppearanceInfoAsync

Resa

Questa funzione restituisce informazioni sull'avatar di un Giocatore(ignorando l'Equipaggiamento) sul sito Web di Roblox sotto forma di dizionario.Non deve essere confuso con GetCharacterAppearanceAsync , che in realtà carica le risorse descritte da questo metodo.Puoi usare InsertService:LoadAsset() per caricare le risorse che vengono utilizzate nell'Avatardel Giocatore.La struttura del dizionario restituito è la seguente:


<th>Tipo</th>
<th>Descrizione</th>
</tr>
</thead>
<tr>
<td><code>risorse</code></td>
<td>tabella (vedi sotto)</td>
<td>Descrive le risorse equipaggiate (tappi, parti del corpo, ecc)</td>
</tr>
<tr>
<td><code>colori del corpo</code></td>
<td>tabella (vedi sotto)</td>
<td>Descrive i valori di BrickColor per ciascun arti</td>
</tr>
<tr>
<td><code>coloreCorpo3s</code></td>
<td>tabella (vedi sotto)</td>
<td>Descrive l'istanza Color3 per ciascun arti che potrebbe non essere perfettamente abbinata ai colori del corpo</td>
</tr>
<tr>
<td><code>默认裤子应用ato</code></td>
<td>bool</td>
<td>Descrive se vengono applicati i pantaloni predefiniti</td>
</tr>
<tr>
<td><code>defaultShirtApplied</code></td>
<td>bool</td>
<td>Descrive se la camicia predefinita viene applicata</td>
</tr>
<tr>
<td><code>emoticon</code></td>
<td>tabella (vedi sotto)</td>
<td>Descrive le animazioni emote equipaggiate</td>
</tr>
<tr>
<td><code>playerAvatarTipo</code></td>
<td>stringa</td>
<td>Oppure "R15" o "R6"</td>
</tr>
<tr>
<td><code>scali</code></td>
<td>tabella (vedi sotto)</td>
<td>Descrive vari fattori di ridimensionamento del corpo</td>
</tr>
Nome
Assets Sottotavola

La tabella assets è un array di tabelle che contiene le seguenti chiavi che descrivono le risorse attualmente equipaggiate dal Giocatore:


<th>Tipo</th>
<th>Descrizione</th>
</tr>
</thead>
<tr>
<td><code>id</code></td>
<td>numbero</td>
<td>L'ID risorsa dell'asset equipaggiato</td>
</tr>
<tr>
<td><code>assetType</code></td>
<td>tavola</td>
<td>Un tavolo con i campi <code>nome</code> e <code>id</code>, ognuno dei quali descrive il tipo di risorsa equipaggiata ("Cappello", "Faccia", ecc.)</td>
</tr>
<tr>
<td><code>nome</code></td>
<td>stringa</td>
<td>Il nome della risorsa equipaggiata</td>
</tr>
Nome
Sub-Tabella delle Bilance

La tabella scales ha le seguenti chiavi, ognuna delle quali corrisponde a una Proprietàdi ridimensionamento Humanoid : bodyType , head , height , proportion , depth , width .

Sottotavola dei colori del corpo

La tabella bodyColors ha le seguenti chiavi, ognuna delle quali è un numero corrispondente a un ID BrickColor che può essere utilizzato con BrickColor.new(id) : leftArmColorId , torsoColorId , rightArmColorId , headColorId , leftLegColorId , rightLegColorId .

Parametri

userId: number

L'ID* di cui sopra del Giocatorespecificato.

Valore predefinito: ""

Restituzioni

Un dizionario che contiene informazioni sull'aspetto del personaggio di un dato utente.

Campioni di codice

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

Resa

La funzione GetFriends Players restituisce un oggetto FriendPages che contiene informazioni per tutti gli amici dell'utente dato.Gli elementi all'interno dell'oggetto FriendPages sono tabelle con i seguenti campi:


<th>Tipo</th>
<th>Descrizione</th>
</tr>
</thead>
<tr>
<td>Id</td>
<td>int64</td>
<td>L'ID utente del Amico/Amica</td>
</tr>
<tr>
<td>Nome utente</td>
<td>stringa</td>
<td>Il Nome utentedell'Amico/Amica</td>
</tr>
<tr>
<td>Nome da mostrare</td>
<td>stringa</td>
<td>Il <code>Class.Player.DisplayName|display name</code> dell'Amico/Amica.</td>
</tr>
Nome

Vedi gli esempi di codice per un modo semplice per itterare su tutti gli amici di un Giocatore.

Parametri

userId: number

L'ID utente del giocatore specificato.

Valore predefinito: ""

Restituzioni

Campioni di codice

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

Resa

Restituisce la descrizione umanoide per un ID outfit specificato, che verrà impostato con le parti/colori/Animazioni ecc dell'outfit.Un outfit può essere uno creato da un utente, o può essere l'outfit per un bundle creato da Roblox.

Parametri

outfitId: number

L'ID dell'outfit per il quale viene cercata la Descrizione Umanoide.

Valore predefinito: ""

Restituzioni

Descrizione umanoide inizializzata con la specifica per l'outfitId passato.

Campioni di codice

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

Resa

Restituisce una descrizione umanoide che specifica tutto ciò che è equipaggiato per l'avatar dell'utente specificato dall'userId inserito.Include anche scale e colori del corpo.

Parametri

userId: number

L'ID utente per un utente Roblox. (L'ID utente è il numero nel profilo dell'utente ad esempio www.roblox.com/users/1/profile).

Valore predefinito: ""

Restituzioni

Descrizione umanoide inizializzata con la specificazione dell'avatar del mittente.

Campioni di codice

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

Resa

La funzione GetNameFromUserIdAsync Players invierà una query al sito Web di Roblox chiedendo quale sia il nome utente dell'account con il UserId dato.

Questo metodo errorifica se non esiste un account con l'ID utente specificato.Se non sei sicuro che un account del genere esista, è consigliato avvolgere le chiamate a questa funzione con pcall() .Inoltre, puoi archiviare manualmente i risultati per rendere le chiamate future con lo stesso UserId veloci.Vedi gli esempi di codice per saperne di più.

Parametri

userId: number

Il Player.UserId del giocatore che viene specificato.

Valore predefinito: ""

Restituzioni

Il nome di un utente con il Player.UserId.

Campioni di codice

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

Resa

Questa funzione invierà una query al sito Web di Roblox chiedendo quale sia il Player.UserId del conto con il nome Player dato.

Questo metodo errorifica se non esiste un account con il Nome utentespecificato.Se non sei sicuro che un account del genere esista, è consigliato avvolgere le chiamate a questa funzione con pcall() .Inoltre, puoi archiviare manualmente i risultati per fare rapidamente chiamate future con lo stesso Nome utente.Vedi gli esempi di codice per saperne di più.

Parametri

userName: string

Il nome utente del giocatore specificato.

Valore predefinito: ""

Restituzioni

Il Player.UserId di un utente il cui nome è specificato.

Campioni di codice

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

Resa

Questa funzione restituisce l'URL del contenuto di un'immagine dell'avatar di un Giocatoredato il loro UserId , la dimensione dell'immagine desiderata come un enum Enum.ThumbnailSize e il tipo desiderato come un enum Enum.ThumbnailType.Restituisce anche un booleano che descrive se l'immagine è pronta all'uso.

La maggior parte delle volte, questo metodo viene utilizzato con ImageLabel.Image o Decal.Texture per visualizzare le immagini dell'avatar dell'utente in un'esperienza.

Parametri

userId: number

Il Player.UserId del giocatore che viene specificato.

Valore predefinito: ""
thumbnailType: Enum.ThumbnailType

A Enum.ThumbnailType descrivendo il tipo di Miniatura.

Valore predefinito: ""
thumbnailSize: Enum.ThumbnailSize

Un Enum.ThumbnailSize che specifica le dimensioni della Miniatura.

Valore predefinito: ""

Restituzioni

Un tuple che contiene l'URL del contenuto di una miniatura utente in base ai parametri specificati e un bool che descrive se l'immagine è pronta per essere utilizzata o meno.

Campioni di codice

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

()
Resa

Sblocca i giocatori bannati da Players:BanAsync() o dalla Restrizioni utente Open Cloud API.Questo metodo è abilitato e disabilitato dalla ProprietàPlayers.BanningEnabled, che puoi attivare in Studio.

Come Players:BanAsync() , questo metodo prende in un dizionario config che ti consentirà di disbanire in blocco gli utenti.Questo configura gli utenti che sono non bloccati e l'ambito da cui sono non bloccati.

Gli sblocchi avranno effetto solo sui divieti con la stessa ApplyToUniverse scala.Ad esempio, un unban con ApplyToUniverse impostato su true non invaliderà un precedente ban con ApplyToUniverse impostato su false .In altre parole, un divieto di livello universo non invaliderà un bandiredi livello posto.Anche l'opposto è vero.

Questo metodo invoca una chiamata HTTP ai servizi backend, che vengono limitati e possono fallire.Se stai chiamando questa API con più UserIds, questo metodo cercherà di fare questa chiamata HTTP per ciascun UserId.Quindi aggregherà tutti i messaggi di errore e li unirà come una lista separata da virgola.Ad esempio, se questo metodo viene invocato per cinque UserIds : {1, 2, 3, 4, 5} e richieste per gli utenti 2 e 4 falliscono allora appare il seguente messaggio di errore: HTTP failure for UserId 2: Timedout, HTTP 504 (Service unavailable) failure for UserId 4: Service exception. Il messaggio includerà sempre failure for UserId {} se è un errore HTTP.È un comportamento non definito se passi in entrambi gli UserIds validi e non validi, cioèun UserId che non è un numero positivo, poiché alcune richieste di rete possono avere successo prima che tutti gli input vengano validati.

A causa dei rischi associati al divieto di utenti, questo metodo può essere chiamato solo sul Serverdi gioco backend.Le chiamate lato client daranno luogo a un errore.Puoi testare questa API in Studio, Team Create e Team Test, ma i divieti non si applicheranno alla produzione.Questa chiamata di funzione tenterà solo richieste di divieto sui server di gioco di produzione e non durante i test in Studio.Tuttavia, tutti i passaggi di validazione dell'input funzioneranno ancora in Studio.

Questa API utilizza la Restrizioni utente Open Cloud API. Potrai utilizzare queste API per gestire i tuoi divieti in applicazioni di terze parti.

Parametri

config: Dictionary

<th>Tipo</th>
<th>Descrizione</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>ID utente</code></td>
<td>vettore</td>
<td>ID utente da forzare nell'esperienza(i). La dimensione massima è <code>50</code>.</td>
</tr>
<tr>
<td><code>Applica a Universo</code></td>
<td>booleano</td>
<td>Propaga il divieto a tutti i luoghi all'interno di questo universo.</td>
</tr>
</tbody>
Nome
Valore predefinito: ""

Restituzioni

()

Campioni di codice

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

Eventi

PlayerAdded

Questo evento si attiva quando un giocatore entra nel Gioco.Questo viene utilizzato per lanciare un evento quando un giocatore si unisce a un Gioco, come il caricamento dei dati salvati del GiocatoreGlobalDataStore .

Questo può essere utilizzato insieme all'evento Players.PlayerRemoving , che si attiva quando un giocatore è about to leave the Gioco.Ad esempio, se vuoi stampare un messaggio ogni volta che un nuovo giocatore si unisce o lascia il Gioco:


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)

Se vuoi tracciare quando il personaggio di un Giocatoreviene aggiunto o rimosso dal Gioco, come quando un giocatore respawna o muore, puoi usare le funzioni Player.CharacterAdded e Player.CharacterRemoving.

Si noti che questo evento non funziona come previsto in Modalità Gioco perché il giocatore viene creato prima che gli script si connettano a PlayerAdded.Per gestire questo caso, così come casi in cui lo script viene aggiunto nel gioco dopo l'ingresso di un giocatore, crea una funzione onPlayerAdded() che puoi chiamare per gestire l'ingresso di un Giocatore.

Parametri

player: Player

Un'istanza del giocatore che si è unito al Gioco.


Campioni di codice

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

Questo evento si attiva quando il server di gioco riconosce che la membership di un Giocatoreè cambiata.Nota, tuttavia, che il server controllerà e aggiornerà solo la membership dopo che la modalità Premium è stata chiusa.Quindi, per tenere conto dei casi in cui l'utente acquista Premium fuori del gioco mentre gioca, devi ancora richiedere loro di acquistare Premium; questo mostrerà quindi un messaggio che dice loro che sono già stati aggiornati e, una volta chiusa la modalità, il server del gioco aggiornerà la loro iscrizione e attiverà questo evento.

Per saperne di più e incorporare Premium nella tua esperienza e monetizzare con il sistema di pagamenti basato sull'engagement, vedi Pagamenti basati sull'engagement.

Vedi anche:

Parametri

player: Player

Campioni di codice

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

L'evento PlayerRemoving si attiva subito prima che un Player lasci il Gioco.Questo evento si attiva prima di ChildRemoved fa su Players , e si comporta in modo leggermente simile a Instance.DescendantRemoving .Dal momento che si attiva prima della rimozione effettiva di un Player , questo evento è utile per archiviare i dati del giocatore utilizzando un GlobalDataStore .

Questo può essere utilizzato insieme all'evento Player.PlayerAdded , che si attiva quando un giocatore si unisce al Gioco.Ad esempio, per stampare un messaggio ogni volta che un nuovo giocatore si unisce o lascia il Gioco:


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)

Se vuoi tracciare quando il personaggio di un Giocatoreviene aggiunto o rimosso dal Gioco, come quando un giocatore respawna o muore, puoi usare le funzioni Player.CharacterAdded e Player.CharacterRemoving.

Parametri

player: Player

Un'istanza del giocatore che sta lasciando il Gioco.


Campioni di codice

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

Questo evento si attiva quando il server di gioco riconosce che lo stato dell'utente per una determinata sottoscrizione è cambiato.Nota che il server tenta di controllare e aggiornare lo stato solo dopo che la modalità Acquisto di Sottoscrizione è stata chiusa.Per tenere conto dei casi in cui l'utente acquista l'abbonamento fuori del gioco mentre gioca, devi comunque richiedere loro di acquistare l'abbonamento; il prompt mostra un messaggio che dice all'utente che è già iscritto e dopo che chiude la modalità, il server del gioco aggiorna lo stato dell'abbonamento e attiva questo evento.

Nota che solo gli script del server ricevono questo evento.

Parametri

user: Player

Utente il cui stato di abbonamento è cambiato.

subscriptionId: string

L'ID dell'abbonamento con un cambio di stato.