✓ Accepted answer
There isn't enough code here to determine exactly what you problem is. For example, I don't know if you are instantiating the leaderstats or not.
However there is a glaring logic error that I can see. You are using elseif, which will only execute if the condition of the if statement that came before it wasn't true. You want to count EVERY badge the player owns not just the first one.
Cascading if statements is not the best way to accomplish this. It would be more efficient to loop over an array of the badge IDs.
####Example:
local BadgeService = game:GetService("BadgeService")
local badges = {229929415, 229929797, 229929912}
local function countBadges(player)
local numBadges = 0
for _, badge in next, badges do
if BadgeService:UserHasBadge(player.userId, badge) then
numBadges = numBadges + 1
end
end
return numBadges
end
game.Players.PlayerAdded:connect(function(player)
local leaderstats = Instance.new("Folder", player)
leaderstats.Name = "leaderstats"
local badges = Instance.new("IntValue", leaderstats)
badges.Value = countBadges(player)
end)
EDIT
local BadgeService = game:GetService("BadgeService")
local badges = {229929415, 229929797, 229929912}
local function countBadges(player)
local numBadges = 0
for _, badge in next, badges do
if BadgeService:UserHasBadge(player.userId, badge) then
numBadges = numBadges + 1
end
end
return numBadges
end
game.Players.PlayerAdded:connect(function(player)
local stats = player:findFirstChild("leaderstats")
local cash = stats:findFirstChild("Badge")
cash.Value = countBadges()
end)
12 comments
I already had an leaderstats, how do i let it work without this leaderstat in the this script?
You remove your if statements and replace it with
cash = countBadges(). Make sure that the countBadges function is in your script.In the leaderboard script ?
See my edit
Error on line 17*
line 17 is wrong, it should say: cash.Value = countBadges(player)
i keep trying diffrent things say still errors
He is right, it should be cash.Value
Line 16 output: attempt to index local 'stats' (a nil value)
You haven't defined the leaderstats, if you use the original answer it defines the leaderstats for you. @BlackJPI, line 17 is still wrong on your edit. It should say countBadges(player). Also, "player.userId" is deprecated and you should use "player.UserId"If you have defined the leaderstats, change the code so it uses :WaitForChild() instead of :findFirstChild()
I tried now with not my custom leaderboard but with an normal one its still not working
Okay i found the problem, userId hadn't to change!