GroupService
*Este conteúdo é traduzido por IA (Beta) e pode conter erros. Para ver a página em inglês, clique aqui.
O GroupService é um serviço que permite que os desenvolvedores recuperem informações sobre um grupo do Roblox de dentro de um jogo.
Informações básicas sobre o grupo, incluindo seu nome, descrição, Proprietário, papéis e emblema podem ser recuperadas usando GroupService:GetGroupInfoAsync().Listas de aliados e inimigos de um grupo podem ser recuperadas usando GroupService:GetAlliesAsync() e GroupService:GetEnemiesAsync().
O GroupService também pode ser usado para obter uma lista de grupos aos quais um jogador é membro, usando GroupService:GetGroupsAsync() .Observe, os desenvolvedores que desejam verificar se um jogador está em um grupo devem usar a função em vez de >.
O serviço tem uma série de aplicações úteis, como detectar se um jogador é aliado ou inimigo ao entrar no jogo.
Amostras de código
This code sample demonstrates how GroupService and Player:IsInGroup() can be used to determine whether a player is a member of a group, or any of its allies or enemies.
Note as GroupService:GetAlliesAsync() and GroupService:GetEnemiesAsync() use StandardPages objects a utility function is used to convert them to allies.
local GroupService = game:GetService("GroupService")
local Players = game:GetService("Players")
-- define group id here
local GROUP_ID = 271454
-- utility function for dealing with pages
local function pagesToArray(pages)
local array = {}
while true do
for _, v in ipairs(pages:GetCurrentPage()) do
table.insert(array, v)
end
if pages.IsFinished then
break
end
pages:AdvanceToNextPageAsync()
end
return array
end
-- get lists of allies and enemies
local alliesPages = GroupService:GetAlliesAsync(GROUP_ID)
local enemiesPages = GroupService:GetEnemiesAsync(GROUP_ID)
-- convert to array
local allies = pagesToArray(alliesPages)
local enemies = pagesToArray(enemiesPages)
local function playerAdded(player)
-- check to see if the player is in the group
if player:IsInGroup(GROUP_ID) then
print(player.Name .. " is a member!")
else
local isAlly, isEnemy = false, false
-- check to see if the player is in any ally groups
for _, groupInfo in ipairs(allies) do
local groupId = groupInfo.Id
if player:IsInGroup(groupId) then
isAlly = true
break
end
end
-- check to see if the player is in any enemy groups
for _, groupInfo in ipairs(enemies) do
local groupId = groupInfo.Id
if player:IsInGroup(groupId) then
isEnemy = true
break
end
end
if isAlly and not isEnemy then
print(player.Name .. " is an ally!")
elseif isEnemy and not isAlly then
print(player.Name .. " is an enemy!")
elseif isEnemy and isAlly then
print(player.Name .. " is both an ally and an enemy!")
else
print(player.Name .. " is neither an ally or an enemy!")
end
end
end
-- listen for new players being added
Players.PlayerAdded:Connect(playerAdded)
-- handle players already in game
for _, player in ipairs(Players:GetPlayers()) do
playerAdded(player)
end
Resumo
Métodos
Retorna um objeto StandardPages incluindo informações sobre todos os aliados do grupo especificado.
Retorna um objeto StandardPages incluindo informações sobre todos os inimigos do grupo especificado.
Retorna uma tabela que contém informações sobre o grupo dado.
Retorna uma lista de tabelas que contêm informações sobre todos os grupos de que um determinado jogador é membro.
Propriedades
Métodos
GetAlliesAsync
Retorna um objeto StandardPages incluindo informações sobre todos os aliados do grupo especificado.
Essas páginas não incluem uma lista de IDs de grupo, mas sim uma lista de tabelas de informações de grupo, refletindo o formato das retornadas por GroupService:GetGroupInfoAsync().Veja abaixo para a estrutura dessas tabelas.
group = {Name = "Knights of the Seventh Sanctum",Id = 377251,Owner = {Name = "Vilicus",Id = 23415609},EmblemUrl = "http://www.roblox.com/asset/?id=60428602",Description = "We fight alongside the balance to make sure no one becomes to powerful",Roles = {[1] = {Name = "Apprentice",Rank = 1},[2] = {Name = "Warrior",Rank = 2},[3] = {Name = "Earth Walker",Rank = 255}}}
Observe, pois esta função retorna um objeto StandardPages que, ao invés de um matriz / lista, os desenvolvedores podem desejar converter em um array para facilitar o uso (veja exemplos).
Essa função tem uma série de aplicações úteis, incluindo detectar se um jogador é membro de um grupo aliado.
Para inimigos, use GroupService:GetEnemiesAsync() .
Parâmetros
O ID do grupo.
Devolução
Amostras de código
local Players = game:GetService("Players")
local GroupService = game:GetService("GroupService")
local GROUP_ID = 57
-- creates a table of all of the allies of a given group
local allies = {}
local pages = GroupService:GetAlliesAsync(GROUP_ID)
while true do
for _, group in pairs(pages:GetCurrentPage()) do
table.insert(allies, group)
end
if pages.IsFinished then
break
end
pages:AdvanceToNextPageAsync()
end
function onPlayerAdded(player)
for _, group in pairs(allies) do
if player:IsInGroup(group.Id) then
print("Player is an ally!")
break
end
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
-- handle players who joined while the allies list was still loading
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
This code sample demonstrates how GroupService and Player:IsInGroup() can be used to determine whether a player is a member of a group, or any of its allies or enemies.
Note as GroupService:GetAlliesAsync() and GroupService:GetEnemiesAsync() use StandardPages objects a utility function is used to convert them to allies.
local GroupService = game:GetService("GroupService")
local Players = game:GetService("Players")
-- define group id here
local GROUP_ID = 271454
-- utility function for dealing with pages
local function pagesToArray(pages)
local array = {}
while true do
for _, v in ipairs(pages:GetCurrentPage()) do
table.insert(array, v)
end
if pages.IsFinished then
break
end
pages:AdvanceToNextPageAsync()
end
return array
end
-- get lists of allies and enemies
local alliesPages = GroupService:GetAlliesAsync(GROUP_ID)
local enemiesPages = GroupService:GetEnemiesAsync(GROUP_ID)
-- convert to array
local allies = pagesToArray(alliesPages)
local enemies = pagesToArray(enemiesPages)
local function playerAdded(player)
-- check to see if the player is in the group
if player:IsInGroup(GROUP_ID) then
print(player.Name .. " is a member!")
else
local isAlly, isEnemy = false, false
-- check to see if the player is in any ally groups
for _, groupInfo in ipairs(allies) do
local groupId = groupInfo.Id
if player:IsInGroup(groupId) then
isAlly = true
break
end
end
-- check to see if the player is in any enemy groups
for _, groupInfo in ipairs(enemies) do
local groupId = groupInfo.Id
if player:IsInGroup(groupId) then
isEnemy = true
break
end
end
if isAlly and not isEnemy then
print(player.Name .. " is an ally!")
elseif isEnemy and not isAlly then
print(player.Name .. " is an enemy!")
elseif isEnemy and isAlly then
print(player.Name .. " is both an ally and an enemy!")
else
print(player.Name .. " is neither an ally or an enemy!")
end
end
end
-- listen for new players being added
Players.PlayerAdded:Connect(playerAdded)
-- handle players already in game
for _, player in ipairs(Players:GetPlayers()) do
playerAdded(player)
end
GetEnemiesAsync
Retorna um objeto StandardPages incluindo informações sobre todos os inimigos do grupo especificado.
Essas páginas não incluem uma lista de IDs de grupo, mas sim uma lista de tabelas de informações de grupo, refletindo o formato das retornadas por GroupService:GetGroupInfoAsync().Veja abaixo para a estrutura dessas tabelas.
group = {Name = "Knights of the Seventh Sanctum",Id = 377251,Owner = {Name = "Vilicus",Id = 23415609},EmblemUrl = "http://www.roblox.com/asset/?id=60428602",Description = "We fight alongside the balance to make sure no one becomes to powerful",Roles = {[1] = {Name = "Apprentice",Rank = 1},[2] = {Name = "Warrior",Rank = 2},[3] = {Name = "Earth Walker",Rank = 255}}}
Observe, pois esta função retorna um objeto StandardPages que, ao invés de um matriz / lista, os desenvolvedores podem desejar converter em um array para facilitar o uso (veja exemplos).
Essa função tem uma série de aplicações úteis, incluindo detectar se um jogador é membro de um grupo inimigo.
Para aliados, use GroupService:GetAlliesAsync() .
Parâmetros
O ID do grupo.
Devolução
Amostras de código
local Players = game:GetService("Players")
local GroupService = game:GetService("GroupService")
local GROUP_ID = 57
-- creates a list of all of the enemies of a given group
local enemies = {}
local pages = GroupService:GetEnemiesAsync(GROUP_ID)
while true do
for _, group in pairs(pages:GetCurrentPage()) do
table.insert(enemies, group)
end
if pages.IsFinished then
break
end
pages:AdvanceToNextPageAsync()
end
function onPlayerAdded(player)
for _, enemyGroup in pairs(enemies) do
if player:IsInGroup(enemyGroup.Id) then
print("Player is an enemy!")
break
end
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
-- handle players who joined while the enemies list was still loading
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
This code sample demonstrates how GroupService and Player:IsInGroup() can be used to determine whether a player is a member of a group, or any of its allies or enemies.
Note as GroupService:GetAlliesAsync() and GroupService:GetEnemiesAsync() use StandardPages objects a utility function is used to convert them to allies.
local GroupService = game:GetService("GroupService")
local Players = game:GetService("Players")
-- define group id here
local GROUP_ID = 271454
-- utility function for dealing with pages
local function pagesToArray(pages)
local array = {}
while true do
for _, v in ipairs(pages:GetCurrentPage()) do
table.insert(array, v)
end
if pages.IsFinished then
break
end
pages:AdvanceToNextPageAsync()
end
return array
end
-- get lists of allies and enemies
local alliesPages = GroupService:GetAlliesAsync(GROUP_ID)
local enemiesPages = GroupService:GetEnemiesAsync(GROUP_ID)
-- convert to array
local allies = pagesToArray(alliesPages)
local enemies = pagesToArray(enemiesPages)
local function playerAdded(player)
-- check to see if the player is in the group
if player:IsInGroup(GROUP_ID) then
print(player.Name .. " is a member!")
else
local isAlly, isEnemy = false, false
-- check to see if the player is in any ally groups
for _, groupInfo in ipairs(allies) do
local groupId = groupInfo.Id
if player:IsInGroup(groupId) then
isAlly = true
break
end
end
-- check to see if the player is in any enemy groups
for _, groupInfo in ipairs(enemies) do
local groupId = groupInfo.Id
if player:IsInGroup(groupId) then
isEnemy = true
break
end
end
if isAlly and not isEnemy then
print(player.Name .. " is an ally!")
elseif isEnemy and not isAlly then
print(player.Name .. " is an enemy!")
elseif isEnemy and isAlly then
print(player.Name .. " is both an ally and an enemy!")
else
print(player.Name .. " is neither an ally or an enemy!")
end
end
end
-- listen for new players being added
Players.PlayerAdded:Connect(playerAdded)
-- handle players already in game
for _, player in ipairs(Players:GetPlayers()) do
playerAdded(player)
end
GetGroupInfoAsync
Retorna uma tabela que contém informações sobre o grupo dado.
A tabela retornada é o mesmo formato que foi retornado em GroupService:GetAlliesAsync() e GroupService:GetEnemiesAsync(). Este formato pode ser visto abaixo.
group = {Name = "Knights of the Seventh Sanctum",Id = 377251,Owner = {Name = "Vilicus",Id = 23415609},EmblemUrl = "http://www.roblox.com/asset/?id=60428602",Description = "We fight alongside the balance to make sure no one becomes to powerful",Roles = {[1] = {Name = "Apprentice",Rank = 1},[2] = {Name = "Warrior",Rank = 2},[3] = {Name = "Earth Walker",Rank = 255}}}
Observe, se um grupo não tem dono, o campo Proprietário será definido como nil.
Essa função tem uma série de aplicações úteis, incluindo carregar a última descrição e logo de um grupo para exibição em uma base de grupo.
Parâmetros
O ID do grupo do grupo.
Devolução
Um dicionário de informações sobre o grupo.
Amostras de código
local GroupService = game:GetService("GroupService")
local GROUP_ID = 377251
local group = GroupService:GetGroupInfoAsync(GROUP_ID)
print(group.Name .. " has the following roles:")
for _, role in ipairs(group.Roles) do
print("Rank " .. role.Rank .. ": " .. role.Name)
end
The code in this sample spawns a Part in the Workspace that includes a texture of the given group's emblem.
local GroupService = game:GetService("GroupService")
local function getEmblemAsync(groupId)
local groupInfo = GroupService:GetGroupInfoAsync(groupId)
return groupInfo.EmblemUrl
end
local part = Instance.new("Part")
part.Anchored = true
part.CanCollide = false
part.Size = Vector3.new(5, 5, 1)
part.Position = Vector3.new(0, 5, 0)
local decal = Instance.new("Decal")
decal.Parent = part
part.Parent = workspace
decal.Texture = getEmblemAsync(377251)
GetGroupsAsync
Aviso/advertência: A propriedade EstáEmClã na tabela retornada sempre retornará falso e existe para a compatibilidade com versões anteriores.A funcionalidade de Clãs foi descontinuada na plataforma Roblox em 2016.
Essa função retorna uma lista de tabelas que contêm informações sobre todos os grupos aos quais um determinado Player é membro.
A lista retornada incluirá uma entrada para cada grupo ao qual o jogador é membro. Essas entradas são tabelas com os seguintes campos.
<th>Descrição</th></tr></thead><tbody><tr><td><b>Qual o nome</b></td><td>O nome do grupo</td></tr><tr><td><b>Id</b></td><td>O ID do grupo</td></tr><tr><td><b>EmblemUrl</b></td><td>Um link de URL para a miniatura do grupo (por exemplo: http://www.roblox.com/asset/?id=276165514)</td></tr><tr><td><b>EmblemId</b></td><td>O assetId do emblema, o mesmo que é usado na EmblemUrl</td></tr><tr><td><b>Classificação</b></td><td>O rankId que o jogador tem (por exemplo: 255 para o Proprietário)</td></tr><tr><td><b>Função</b></td><td>O nome do rank de grupo do jogador (por exemplo: Proprietário do Grupo)</td></tr><tr><td><b>É primário</b></td><td>Um booleano que indica se este é o grupo principal do jogador</td></tr><tr><td><b>Está em Clã</b></td><td>Um booleano que indica se o jogador está no clã deste grupo</td></tr></tbody>
Qual o nome |
---|
Nota ao contrário de GroupService:GetAlliesAsync() e GroupService:GetEnemiesAsync(), GetGroupsAsync retorna uma tabela em vez de um ObjetoStandardPages.
Parâmetros
O Player.UserId do usuário.
Devolução
Amostras de código
This code sample will print information on all of the groups a player is a member of when they join the game, using GroupService:GetGroupsAsync().
local GroupService = game:GetService("GroupService")
local Players = game:GetService("Players")
local function playerAdded(player)
-- load a list of info on all groups the player is a member of
local groups = GroupService:GetGroupsAsync(player.UserId)
for _, groupInfo in pairs(groups) do
for key, value in pairs(groupInfo) do
print(key .. ": " .. tostring(value))
end
print("--")
end
end
Players.PlayerAdded:Connect(playerAdded)
-- go through existing players
for _, player in pairs(Players:GetPlayers()) do
playerAdded(player)
end