Classe motore
Players
*Questo contenuto è tradotto usando AI (Beta) e potrebbe contenere errori. Per visualizzare questa pagina in inglese, clicca qui.
Sommario
Proprietà
Metodi
Eventi
PlayerAdded(player: Player):RBXScriptSignal |
PlayerMembershipChanged(player: Player):RBXScriptSignal |
PlayerRemoving(player: Player,reason: Enum.PlayerExitReason):RBXScriptSignal |
UserSubscriptionStatusChanged(user: Player,subscriptionId: string):RBXScriptSignal |
Riferimento API
Proprietà
CharacterAutoLoads
Campioni di codice
Timer di Respawn del Giocatore
local Players = game:GetService("Players")
-- Imposta CharacterAutoLoads su false
Players.CharacterAutoLoads = false
-- Rimuovi il personaggio del giocatore dallo spazio di lavoro alla morte
Players.PlayerAdded:Connect(function(player)
while true do
local char = player.CharacterAdded:Wait()
char.Humanoid.Died:Connect(function()
char:Destroy()
end)
end
end)
-- Rigenera tutti i giocatori morti ogni 10 secondi
while true do
local players = Players:GetChildren()
-- Controlla se ogni giocatore è morto verificando se non ha personaggio, se è morto carica il personaggio di quel giocatore
for _, player in pairs(players) do
if not workspace:FindFirstChild(player.Name) then
player:LoadCharacterAsync()
end
end
-- Attendi 10 secondi fino al prossimo controllo di rigenerazione
task.wait(10)
endlocalPlayer
NumPlayers
numPlayers
Metodi
BanAsync
Parametri
Restituzioni
()
Campioni di codice
Bannare Utenti
local Players = game:GetService("Players")
if shouldBeBanned(player) then
local banHistoryPages = Players:GetBanHistoryAsync(player.UserId)
local duration = 86400 -- 24 ore in secondi. Raccomandazione: usa la tua logica basata sulla BanHistory dell'utente
local config: BanConfigType = {
UserIds = { player.UserId },
Duration = duration,
DisplayReason = "Hai violato la linea guida della comunità #5",
PrivateReason = "Metti qui qualsiasi cosa che l'utente non dovrebbe sapere ma che è utile per i tuoi registri",
ExcludeAltAccounts = false,
ApplyToUniverse = true,
}
local success, err = pcall(function()
return Players:BanAsync(config)
end)
print(success, err)
endChat
Parametri
Restituzioni
()
Campioni di codice
Giocatori:Chat
-- Command bar
game:GetService("Players"):Chat("Ciao, mondo!") --Risultati in 'Ciao, mondo!' che appare nel log della Chat sotto il nome del tuo Giocatore.
-- Script
local Players = game:GetService("Players")
Players:Chat("Ciao, mondo!") --ErroriCreateHumanoidModelFromDescription
CreateHumanoidModelFromDescriptionAsync
Players:CreateHumanoidModelFromDescriptionAsync(
description:HumanoidDescription, rigType:Enum.HumanoidRigType, assetTypeVerification:Enum.AssetTypeVerification
Parametri
| Valore predefinito: "Default" |
Restituzioni
Campioni di codice
Crea un Modello Umanoide dalla Descrizione
game.Players:CreateHumanoidModelFromDescriptionAsync(Instance.new("HumanoidDescription"), Enum.HumanoidRigType.R15).Parent =
game.WorkspaceCreateHumanoidModelFromUserId
CreateHumanoidModelFromUserIdAsync
GetBanHistoryAsync
Parametri
Restituzioni
GetCharacterAppearanceAsync
GetCharacterAppearanceInfoAsync
Parametri
Restituzioni
Campioni di codice
Esempio di dizionario dell'aspetto del personaggio restituito
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 = "Cappello",
id = 8,
},
name = "Cappello a righe",
},
{
id = 13062491,
assetType = {
name = "Accessorio per il viso",
id = 42,
},
name = "Vision Française ",
},
{
id = 16598440,
assetType = {
name = "Accessorio per il collo",
id = 43,
},
name = "Papillon Rosso",
},
{
id = 28999228,
assetType = {
name = "Viso",
id = 18,
},
name = "Sorpresa Gioiosa",
},
{
id = 86896488,
assetType = {
name = "Camicia",
id = 11,
},
name = "Giacca da smoking rossa costosa",
},
{
id = 86896502,
assetType = {
name = "Pantaloni",
id = 12,
},
name = "Pantaloni da smoking rossi costosi",
},
{
id = 376530220,
assetType = {
name = "Braccio Sinistro",
id = 29,
},
name = "Braccio Sinistro ROBLOX Boy",
},
{
id = 376531012,
assetType = {
name = "Braccio Destro",
id = 28,
},
name = "Braccio Destro ROBLOX Boy",
},
{
id = 376531300,
assetType = {
name = "Gamba Sinistra",
id = 30,
},
name = "Gamba Sinistra ROBLOX Boy",
},
{
id = 376531703,
assetType = {
name = "Gamba Destra",
id = 31,
},
name = "Gamba Destra ROBLOX Boy",
},
{
id = 376532000,
assetType = {
name = "Torso",
id = 27,
},
name = "Torso ROBLOX Boy",
},
},
}
print(result)GetFriendsAsync
Parametri
Restituzioni
Campioni di codice
Stampa amici di Roblox
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
-- Per prima cosa, ottieni l'ID utente del giocatore
local userId = Players:GetUserIdFromNameAsync(USERNAME)
-- Poi, ottieni un oggetto FriendPages per i loro amici
local friendPages = Players:GetFriendsAsync(userId)
-- Itera sugli elementi nelle pagine. Per FriendPages, questi
-- sono tabelle di informazioni sull'amico, incluso il Nome Utente.
-- Raccogli ogni nome utente in un table
local usernames = {}
for item, _pageNo in iterPageItems(friendPages) do
table.insert(usernames, item.Username)
end
print("Connessioni di " .. USERNAME .. ": " .. table.concat(usernames, ", "))GetHumanoidDescriptionFromOutfitId
GetHumanoidDescriptionFromOutfitIdAsync
Parametri
Restituzioni
Campioni di codice
Ottieni HumanoidDescription da 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:GetHumanoidDescriptionFromOutfitIdAsync(itemId)
end
return nil
end
local humanoidDescription = getHumanoidDescriptionBundle(799)
local humanoidModel = Players:CreateHumanoidModelFromDescriptionAsync(humanoidDescription, Enum.HumanoidRigType.R15)
humanoidModel.Parent = WorkspaceGetHumanoidDescriptionFromUserId
GetHumanoidDescriptionFromUserIdAsync
Parametri
Restituzioni
Campioni di codice
Ottieni HumanoidDescription da User ID
game.Players:CreateHumanoidModelFromDescriptionAsync(
game.Players:GetHumanoidDescriptionFromUserIdAsync(1),
Enum.HumanoidRigType.R15
).Parent =
game.WorkspaceGetNameFromUserIdAsync
Parametri
Restituzioni
Campioni di codice
Ottieni nome da UserId
local Players = game:GetService("Players")
-- Dati di esempio:
-- UserId: 118271 Nome: "RobloxRulez"
-- UserId: 131963979 Nome: "docsRule"
local nameOne = Players:GetNameFromUserIdAsync(118271)
local nameTwo = Players:GetNameFromUserIdAsync(131963979)
print(nameOne, nameTwo)
-- stampa: "RobloxRulez docsRule"Ottieni il nome da UserId utilizzando una cache
local Players = game:GetService("Players")
-- Crea una tabella chiamata 'cache' per memorizzare ogni 'Name' man mano che vengono trovati.
-- Se cerchiamo un 'Name' usando lo stesso 'UserId', il 'Name' verrà
-- dalla cache (veloce) invece di GetNameFromUserIdAsync() (restituisce).
local cache = {}
function getNameFromUserId(userId)
-- Prima di tutto, controlla se la cache contiene 'userId'
local nameFromCache = cache[userId]
if nameFromCache then
-- se un valore è stato memorizzato nella cache con chiave 'userId', allora questo 'nameFromCache'
-- è il Name corretto e possiamo restituirlo.
return nameFromCache
end
-- Se qui, 'userId' non è stato precedentemente cercato e non esiste nella
-- cache. Ora dobbiamo usare GetNameFromUserIdAsync() per cercare il nome
local name
local success, _ = pcall(function()
name = Players:GetNameFromUserIdAsync(userId)
end)
if success then
-- se 'success' è true, GetNameFromUserIdAsync() ha trovato il
-- nome. Memorizza questo nome nella cache usando 'userId' come chiave così non
-- dobbiamo più cercare questo nome in futuro. Poi restituisci name.
cache[userId] = name
return name
end
-- Se qui, 'success' è stato false, il che significa che GetNameFromUserIdAsync()
-- non è riuscito a trovare il 'name' per il 'userId' fornito. Avvisa l'utente
-- che è successo e poi restituisci nulla, o nil.
warn("Impossibile trovare il Nome per UserId:", userId)
return nil
end
-- Dati di esempio:
-- UserId: 118271 Nome: "RobloxRulez"
-- UserId: 131963979 Nome: "docsRule"
-- La prima volta che viene usato un UserId, verrà chiamato GetNameFromUserIdAsync()
local nameOne = getNameFromUserId(118271)
local nameTwo = getNameFromUserId(131963979)
-- Poiché 118271 è stato precedentemente usato, ottieni il suo Nome dalla cache
local nameOneQuick = getNameFromUserId(118271)
print(nameOne, nameTwo, nameOneQuick)
-- stampa: "RobloxRulez docsRule RobloxRulez"GetPlayerByUserId
Parametri
Restituzioni
Campioni di codice
Players:GetPlayerByUserId
local Players = game:GetService("Players")
local player = Players:GetPlayerByUserId(1)
if player then
print("Il giocatore con userId 1 è in questo server! Il suo nome è: " .. player.Name)
else
print("Il giocatore con userId 1 non è in questo server!")
endGetPlayerFromCharacter
Parametri
Restituzioni
Campioni di codice
Giocatori: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(`Giocatore {player.Name} ({player.UserId}) è nel gioco`)
else
print(`Giocatore {PLAYER_NAME} non è nel gioco!`)
endGetPlayers
Restituzioni
{Player}
Campioni di codice
Dare Glitter a Tutti
local Players = game:GetService("Players")
local function onCharacterAdded(character)
-- Dare loro dei glitter in testa se non ce l'hanno già
if not character:FindFirstChild("Sparkles") then
local sparkles = Instance.new("Sparkles")
sparkles.Parent = character:WaitForChild("Head")
end
end
local function onPlayerAdded(player)
-- Controlla se sono già stati creati
if player.Character then
onCharacterAdded(player.Character)
end
-- Ascolta il giocatore che (ri)spawna
player.CharacterAdded:Connect(onCharacterAdded)
end
Players.PlayerAdded:Connect(onPlayerAdded)getPlayers
GetUserIdFromNameAsync
Parametri
Restituzioni
Campioni di codice
Ottieni UserId da Nome
local Players = game:GetService("Players")
-- Dati di esempio:
-- UserId: 118271 Nome: "RobloxRulez"
-- UserId: 131963979 Nome: "docsRule"
local userIdOne = Players:GetUserIdFromNameAsync("RobloxRulez")
local userIdTwo = Players:GetUserIdFromNameAsync("docsRule")
print(userIdOne, userIdTwo)
-- stampa: "118271 131963979"Ottieni UserId da Nome utilizzando una cache
local Players = game:GetService("Players")
-- Crea una tabella chiamata 'cache' per memorizzare ogni 'UserId' man mano che vengono trovati.
-- Se cerchiamo un 'UserId' usando lo stesso 'Nome', l''UserId' verrà
-- dalla cache (veloce) invece di GetUserIdFromNameAsync() (produce).
local cache = {}
function getUserIdFromName(name)
-- Prima, controlla se la cache contiene 'name'
local userIdFromCache = cache[name]
if userIdFromCache then
-- se un valore è stato memorizzato nella cache con la chiave 'name', allora questo 'userIdFromCache'
-- è il corretto UserId e possiamo restituirlo.
return userIdFromCache
end
-- Se qui, 'name' non è stato cercato in precedenza e non esiste nella
-- cache. Ora dobbiamo usare GetUserIdFromNameAsync() per cercare il userId
local userId
local success, _ = pcall(function()
userId = Players:GetUserIdFromNameAsync(name)
end)
if success then
-- se 'success' è vero, GetUserIdFromNameAsync() ha trovato con successo il
-- userId. Memorizza questo userId nella cache utilizzando 'name' come chiave così non
-- dobbiamo mai cercare questo userId in futuro. Poi restituisci userId.
cache[name] = userId
return userId
end
-- Se qui, 'success' era falso, il che significa che GetUserIdFromNameAsync()
-- non è stato in grado di trovare il 'userId' per il 'name' fornito. Possiamo avvisare il
-- utente che è successo e poi restituire nulla, o nil.
warn("Impossibile trovare UserId per Nome:", name)
return nil
end
-- Dati di esempio:
-- UserId: 118271 Nome: "RobloxRulez"
-- UserId: 131963979 Nome: "docsRule"
-- La prima volta che viene utilizzato un Nome, verrà chiamato GetUserIdFromNameAsync()
local userIdOne = getUserIdFromName("RobloxRulez")
local userIdTwo = getUserIdFromName("docsRule")
-- Poiché "RobloxRulez" è stato usato in precedenza, ottiene il suo UserId dalla cache
local userIdOneQuick = getUserIdFromName("RobloxRulez")
print(userIdOne, userIdTwo, userIdOneQuick)
-- stampa: "118271 131963979 118271"GetUserThumbnailAsync
Players:GetUserThumbnailAsync(
Parametri
Restituzioni
Campioni di codice
Visualizza la miniature del giocatore
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local PLACEHOLDER_IMAGE = "rbxassetid://0" -- sostituisci con l'immagine segnaposto
-- recupera la miniature
local userId = player.UserId
local thumbType = Enum.ThumbnailType.HeadShot
local thumbSize = Enum.ThumbnailSize.Size420x420
local content, isReady = Players:GetUserThumbnailAsync(userId, thumbType, thumbSize)
-- imposta il contenuto dell'ImageLabel sulla miniature dell'utente
local imageLabel = script.Parent
imageLabel.Image = (isReady and content) or PLACEHOLDER_IMAGE
imageLabel.Size = UDim2.new(0, 420, 0, 420)playerFromCharacter
players
SetChatStyle
Parametri
| Valore predefinito: "Classic" |
Restituzioni
()
Campioni di codice
Impostazione dello Stile di Chat di un Giocatore
-- Command bar
game.Players:SetChatStyle(Enum.ChatStyle.Classic) -- Imposta lo stile di chat su Classic
-- LocalScript
local Players = game:GetService("Players")
Players:SetChatStyle(Enum.ChatStyle.Classic) -- ErroriTeamChat
Parametri
Restituzioni
()
Campioni di codice
Invio Chat di Squadra
-- Command bar
game.Players:TeamChat("Ciao Mondo") -- Invia un messaggio "Ciao Mondo" a tutti i giocatori nella squadra del giocatore locale
-- LocalScript
local Players = game:GetService("Players")
Players:TeamChat("Ciao Mondo") -- ErroriUnbanAsync
Parametri
Restituzioni
()
Campioni di codice
Riaprire gli utenti
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)
endEventi
PlayerAdded
Parametri
Campioni di codice
Giocatori.PlayerAdded
local Players = game:GetService("Players")
local function onPlayerAdded(player)
print("Un giocatore è entrato: " .. player.Name)
end
Players.PlayerAdded:Connect(onPlayerAdded)PlayerMembershipChanged
Parametri
Campioni di codice
Gestire le modifiche all'iscrizione Premium
local Players = game:GetService("Players")
local function grantPremiumBenefits(player)
-- Concedi al giocatore l'accesso a aree e oggetti riservati ai Premium, o qualunque cosa tu possa immaginare!
print("Concessione", player, "benefici premium!")
end
local function playerAdded(player)
if player.MembershipType == Enum.MembershipType.Premium then
grantPremiumBenefits(player)
end
end
local function playerMembershipChanged(player)
print("Ricevuto evento PlayerMembershipChanged. Nuova iscrizione = " .. tostring(player.MembershipType))
if player.MembershipType == Enum.MembershipType.Premium then
grantPremiumBenefits(player)
end
end
Players.PlayerAdded:Connect(playerAdded)
Players.PlayerMembershipChanged:Connect(playerMembershipChanged)PlayerRemoving
Parametri
Campioni di codice
Giocatori.PlayerRemoving
local Players = game:GetService("Players")
local function onPlayerRemoving(player)
print("Un giocatore è uscito: " .. player.Name)
end
Players.PlayerRemoving:Connect(onPlayerRemoving)UserSubscriptionStatusChanged