BadgeService

Mostrar obsoleto

*Este conteúdo é traduzido por IA (Beta) e pode conter erros. Para ver a página em inglês, clique aqui.

Não criável
Serviço

A classe Serviço de Emblema fornece informações e funcionalidades relacionadas a emblemas.Insígnias são usadas em toda a plataforma para reconhecer as conquistas e a atividade de um jogador.Ao conceder uma insígnia a um jogador, ela é adicionada ao seu inventário e exibida na página de perfil deles.

Amostras de código

The following example creates an awardBadge() function that handles potential errors that may occur when awarding a badge. Using properties of the badge fetched via BadgeService:GetBadgeInfoAsync(), it confirms that the badge can be awarded and does so using BadgeService:AwardBadge().

Awarding a Badge

local BadgeService = game:GetService("BadgeService")
local Players = game:GetService("Players")
local BADGE_ID = 0
local function awardBadge(player, badgeId)
-- Fetch badge information
local success, badgeInfo = pcall(function()
return BadgeService:GetBadgeInfoAsync(badgeId)
end)
if success then
-- Confirm that badge can be awarded
if badgeInfo.IsEnabled then
-- Award badge
local awardSuccess, result = pcall(function()
return BadgeService:AwardBadge(player.UserId, badgeId)
end)
if not awardSuccess then
-- the AwardBadge function threw an error
warn("Error while awarding badge:", result)
elseif not result then
-- the AwardBadge function did not award a badge
warn("Failed to award badge.")
end
end
else
warn("Error while fetching badge info: " .. badgeInfo)
end
end
local function onPlayerAdded(player)
awardBadge(player, BADGE_ID)
end
Players.PlayerAdded:Connect(onPlayerAdded)

The following script waits for any player to enter the game and checks if they own a specific badge. This is useful for creating a restricted area with collision filtering or teleportation that only works if a player owns a special badge.

Checking Earned Badges

local BadgeService = game:GetService("BadgeService")
local Players = game:GetService("Players")
local badgeId = 00000000 -- Change this to your badge ID
local function onPlayerAdded(player)
-- Check if the player has the badge
local success, hasBadge = pcall(function()
return BadgeService:UserHasBadgeAsync(player.UserId, badgeId)
end)
-- If there's an error, issue a warning and exit the function
if not success then
warn("Error while checking if player has badge!")
return
end
if hasBadge then
-- Handle player's badge ownership as needed
print(player.Name, "has badge", badgeId)
end
end
-- Connect "PlayerAdded" events to the "onPlayerAdded()" function
Players.PlayerAdded:Connect(onPlayerAdded)

This script checks which badges a user owns when they join the experience.

Checking Earned Badges in Batches

local BadgeService = game:GetService("BadgeService")
local Players = game:GetService("Players")
local badgeIds = { 0000000000, 1111111111, 2222222222 } -- Change this to a list of your badge IDs
local function onPlayerAdded(player)
-- Check if the player has any of the badges
local success, result = pcall(function()
return BadgeService:CheckUserBadgesAsync(player.UserId, badgeIds)
end)
-- If there's an error, issue a warning and exit the function
if not success then
warn("Error while checking if player", player.Name, "has badges:", result)
return
end
local ownedBadgeIds = result
if #ownedBadgeIds == 0 then
print(player.Name, "does not have any of the badges")
else
print(player.Name, "has the following badges:", table.concat(ownedBadgeIds, ", "))
end
end
Players.PlayerAdded:Connect(onPlayerAdded)

This sample prints badge information fetched via BadgeService:GetBadgeInfoAsync().

Getting Badge Info

local BadgeService = game:GetService("BadgeService")
-- Fetch badge information
local success, result = pcall(function()
return BadgeService:GetBadgeInfoAsync(00000000) -- Change this to desired badge ID
end)
-- Output the information
if success then
print("Badge:", result.Name)
print("Enabled:", result.IsEnabled)
print("Description:", result.Description)
print("Icon:", "rbxassetid://" .. result.IconImageId)
else
warn("Error while fetching badge info:", result)
end

Resumo

Métodos

Propriedades

Métodos

AwardBadge

Rendimentos

Concede a Player uma insígnia com o UserId e o ID da insígnia.Limite de taxa: 50 + 35 * [number of users] por minuto .Para conceder com sucesso uma emblema:

  • O jogador deve estar conectado ao jogo atualmente.
  • O jogador não deve já ter o emblema (note que um jogador pode excluir um emblema concedido de seu perfil e ser premiado o emblema novamente).
  • A insígnia deve ser concedida de um lado do servidor Script ou de um ModuleScript eventualmente exigido por um Script , não de um LocalScript .
  • A insígnia deve ser concedida em um local que faz parte do jogo associado à emblema.
  • O distintivo deve ser habilitado; verifique isso usando a propriedade IsEnabled do distintivo obtido através de BadgeService:GetBadgeInfoAsync() .

Veja também:

Parâmetros

userId: number

O Player.UserId do usuário ao qual a insígnia será concedida.

Valor Padrão: ""
badgeId: number

O ID da insígnia a ser concedida.

Valor Padrão: ""

Devolução

Booleano de true se a insígnia foi concedida com sucesso.

Amostras de código

The following example creates an awardBadge() function that handles potential errors that may occur when awarding a badge. Using properties of the badge fetched via BadgeService:GetBadgeInfoAsync(), it confirms that the badge can be awarded and does so using BadgeService:AwardBadge().

Awarding a Badge

local BadgeService = game:GetService("BadgeService")
local Players = game:GetService("Players")
local BADGE_ID = 0
local function awardBadge(player, badgeId)
-- Fetch badge information
local success, badgeInfo = pcall(function()
return BadgeService:GetBadgeInfoAsync(badgeId)
end)
if success then
-- Confirm that badge can be awarded
if badgeInfo.IsEnabled then
-- Award badge
local awardSuccess, result = pcall(function()
return BadgeService:AwardBadge(player.UserId, badgeId)
end)
if not awardSuccess then
-- the AwardBadge function threw an error
warn("Error while awarding badge:", result)
elseif not result then
-- the AwardBadge function did not award a badge
warn("Failed to award badge.")
end
end
else
warn("Error while fetching badge info: " .. badgeInfo)
end
end
local function onPlayerAdded(player)
awardBadge(player, BADGE_ID)
end
Players.PlayerAdded:Connect(onPlayerAdded)

CheckUserBadgesAsync

Rendimentos

Verifica uma lista de IDs de insígnia contra um UserId e retorna uma lista de IDs de insígnia que o jogador possui.

Este método suporta lotes de até 10 insígnias. Use BadgeService:UserHasBadgeAsync() para pesquisas de insígnia única.

Limite de taxa: 10 + 5* [number of players] por minuto em cada servidor.

Qualquer conjunto de insígnias para qualquer experiência pode ser consultado, não importa quem criou as insígnias ou para quais experiências elas são.Qualquer UserId pode ser usado em um Script , mas em um LocalScript , apenas o UserId do usuário local cujo cliente está executando o script pode ser usado.

Parâmetros

userId: number

O UserId do jogador para verificar a propriedade das insígnias especificadas.

Valor Padrão: ""
badgeIds: Array

A lista de IDs dos distintivos para verificar a propriedade. Comprimento máximo de 10.

Valor Padrão: ""

Devolução

A lista de IDs de insígnia que o usuário dado possui fora dos IDs de insígnia fornecidos.Vazio se nenhuma das insígnias fornecidas for possuída pelo usuário fornecido.Não garantido de estar na mesma ordem que a lista de entrada.

Amostras de código

This script checks which badges a user owns when they join the experience.

Checking Earned Badges in Batches

local BadgeService = game:GetService("BadgeService")
local Players = game:GetService("Players")
local badgeIds = { 0000000000, 1111111111, 2222222222 } -- Change this to a list of your badge IDs
local function onPlayerAdded(player)
-- Check if the player has any of the badges
local success, result = pcall(function()
return BadgeService:CheckUserBadgesAsync(player.UserId, badgeIds)
end)
-- If there's an error, issue a warning and exit the function
if not success then
warn("Error while checking if player", player.Name, "has badges:", result)
return
end
local ownedBadgeIds = result
if #ownedBadgeIds == 0 then
print(player.Name, "does not have any of the badges")
else
print(player.Name, "has the following badges:", table.concat(ownedBadgeIds, ", "))
end
end
Players.PlayerAdded:Connect(onPlayerAdded)

GetBadgeInfoAsync

Rendimentos

Essa função busca informações sobre uma insígnia dada seu ID.Demora um breve momento para carregar as informações do site do Roblox; chamadas repetidas serão armazenadas por um curto período.Ele retorna um dicionário com os seguintes campos:


<th>Tipo</th>
<th>Descrição</th>
</tr>
</thead>
<tbody>
<tr>
<td><b>Qual o nome</b></td>
<td>string / cadeia / texto</td>
<td>O nome da emblema.</td>
</tr>
<tr>
<td><b>Descrição</b></td>
<td>string / cadeia / texto</td>
<td>A descrição da emblema.</td>
</tr>
<tr>
<td><b>Id da Imagem do Ícone</b></td>
<td>int64</td>
<td>O ID da imagem para o emblema.</td>
</tr>
<tr>
<td><b>Está Ativado</b></td>
<td>bool</td>
<td>Indica se a insígnia está disponível para ser concedida.</td>
</tr>
</tbody>
Chave

Veja também:

Parâmetros

badgeId: number

O ID da insígnia da insígnia cuja informação deve ser recuperada.

Valor Padrão: ""

Devolução

Um dicionário de informações sobre a emblemaespecificada.

Amostras de código

This sample prints badge information fetched via BadgeService:GetBadgeInfoAsync().

Getting Badge Info

local BadgeService = game:GetService("BadgeService")
-- Fetch badge information
local success, result = pcall(function()
return BadgeService:GetBadgeInfoAsync(00000000) -- Change this to desired badge ID
end)
-- Output the information
if success then
print("Badge:", result.Name)
print("Enabled:", result.IsEnabled)
print("Description:", result.Description)
print("Icon:", "rbxassetid://" .. result.IconImageId)
else
warn("Error while fetching badge info:", result)
end

UserHasBadgeAsync

Rendimentos

Verifica e retorna se um Player possui um distintivo dado seu UserId e o ID do distintivo.Limite de taxa: 50 + 35 * [number of players] por minuto .Você pode chamar a função do servidor em um Script ou ModuleScript eventualmente exigido por um Script e o usuário em questão deve estar presente no servidor para que a consulta seja executar.Ao chamar o método do cliente em um LocalScript , ele só funciona para o usuário local cujo cliente está executando o script.

Qualquer insígnia para qualquer jogo pode ser consultada, não importa quem criou o insígnia ou para qual experiência ele é usado.

Veja também:

Parâmetros

userId: number

O Player.UserId do jogador para verificar a propriedade do emblemaespecificado.

Valor Padrão: ""
badgeId: number

O ID da insígnia do distintivo cuja propriedade será verificada.

Valor Padrão: ""

Devolução

Indica se o usuário especificado tem a emblemaespecificada.

Amostras de código

The following script waits for any player to enter the game and checks if they own a specific badge. This is useful for creating a restricted area with collision filtering or teleportation that only works if a player owns a special badge.

Checking Earned Badges

local BadgeService = game:GetService("BadgeService")
local Players = game:GetService("Players")
local badgeId = 00000000 -- Change this to your badge ID
local function onPlayerAdded(player)
-- Check if the player has the badge
local success, hasBadge = pcall(function()
return BadgeService:UserHasBadgeAsync(player.UserId, badgeId)
end)
-- If there's an error, issue a warning and exit the function
if not success then
warn("Error while checking if player has badge!")
return
end
if hasBadge then
-- Handle player's badge ownership as needed
print(player.Name, "has badge", badgeId)
end
end
-- Connect "PlayerAdded" events to the "onPlayerAdded()" function
Players.PlayerAdded:Connect(onPlayerAdded)

Eventos