Badge giving doesn't work

I was trying to make a badge that was awarded to the player upon starting the game. For some reason it doesn’t seem to work. I got this error

ServerScriptService.AwardWelcomeBadge:6: attempt to index nil with ‘userId’

here’s the script if you see any bugs.
Thank you!

edit: script is located in serverscriptstorage if that helps.

local badgeId = 10129915474
local badgeService = game:GetService("BadgeService")

function award (player)
	wait(1)
	if not badgeService:UserHasBadge(player.userId, badgeId) then
		badgeService:AwardBadge(player.userId,badgeId)
	end
end

game.Players.PlayerAdded:Connect(award())

Instead of game.Players.PlayerAdded:Connect(award())

You should try:

game.Players.PlayerAdded:Connect(function(player)
   award(player)
end)
game.Players.PlayerAdded:Connect(award())

remove the () from award()

you’re calling the function here instead of connecting it to run when that event happens. And it has no parameters so it will error.

also change userId to UserId

1 Like

Use UserHasBadgeAsync instead of UserHasBadge, this isn’t the cause of your issue but the latter is deprecated and thus shouldn’t be used in new work (as per the official documentation guidelines).

Other than that, the wait(1) isn’t really necessary, and you should look into wrapping network calls inside pcall() as to handle any potential errors.

1 Like

Instead, try:

local badgeId = 10129915474
local badgeService = game:GetService("BadgeService")


function award(player)
	task.wait()
	local success,result = pcall(function()
        return badgeService:UserHasBadgeAsync(player.UserId,badgeId)
    end)
    if success then
       if result then -- if he has the badge
        
       else -- if he doesnt have the badge
          --award him here
       end
    end
end

game.Players.PlayerAdded:Connect(award)

guys I’m really sorry for the late response
sorry Robotz doesn’t work