Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Add Value From Badge Listed In A Table?

So what I'm trying to accomplish with this script is to see if a player has a badge listed in the table, and then add a leaderstat value based on that. But I'm not sure what to do after this point.

local bs = game:GetService('BadgeService')

local badgeList = {
	'badge id here',
	'badge id here',
	'badge id here'
}

game.Players.PlayerAdded:Connect(function(player)
	bs:UserHasBadgeAsync(player.UserId, ???)
end)

1 answer

✓ Accepted answer

I modified the example script from the BadgeService/UserHasBadgeAsync API reference so that it goes through the table of badges in your list. I'm not sure if it will work as you intend it to though, I've never worked with pcall functions before.

local bs = game:GetService('BadgeService')

local badgeList = {  
   'badge id here',
   'badge id here',
  'badge id here'
}

local badges = 0  -- how many badges the player owns

local function onPlayerAdded(player)
	for i = 1,#badgeList do  -- for every badge in the table, repeat function
		local value = i  --table index
		-- Check if the player has the badge
		local success, hasBadge = pcall(function()
			return BadgeService:UserHasBadgeAsync(player.UserId, badgeList[value]) --checks if player has the badge corresponding to the value, for example if the value is 2 then the script will check if the player has the second badge in the table
		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
			badges = badges + 1 --add one badge that the player has
			-- Handle player's badge ownership as needed
		end
	end
end
	 
-- Connect "PlayerAdded" events to the "onPlayerAdded()" function
Players.PlayerAdded:Connect(onPlayerAdded)

9 comments

0

Well, the script works but it capped the value at 1 for some reason

0

Wdym by that? Can you describe how you want the script to work?

0

So basically, i have a game where you beat these little minigames/obbies for badges. And when you beat one you get a badge. So with that in mind, i wanted to make a script which counted how many total minigames/obbies you've beaten.

0

Oh ok, I can edit the script. What did you mean by it capping at 1? It's not going down the rest of the table past the 1st string?

0

By capping at 1, i meant the leaderstat i set stopped at 1 instead of continuing, so it probably didn't finish the rest

0

Okay I edited it. I'm not sure if it's going to work. Let me know if it does

0

It worked, thanks!

0

No problem, happy to help

0

I've changed two lines of the script to make it more efficient. If you want, you can apply them. Set value = i and remove the line that adds 1 to the value.

This discussion is preserved as it was. New answers, comments, and votes are closed.