Search code examples
luaroblox

badge giver help (roblox)


So, I'm working on a Roblox game, I want to make a secret room and award players a badge for finding it, but the problem is that the badge giver is not working, my badge giver is also locked so that I don't accidentally put it in a map. It's also behind a code door and surrounded by locked parts. Here is my code.

local badgeService = game:GetService("BadgeService")
local id = 2133435079

script.Parent.Touched:Connect(function(hit)
    
    if hit.Parent:FindFirstChild("Humanoid") then
        
        local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
        badgeService:AwardBadge(plr.UserId,id)
    end
end)

I tried unlocking the badge giver but that didn't work.

I also tried regular test but that also didn't work


Solution

  • Based on the error, it sounds like you're not protecting against the case that plr is nil. This can happen if hit.Parent isn't a player's character model.

    local badgeService = game:GetService("BadgeService")
    local players = game:GetService("Players")
    local id = 2133435079
    
    script.Parent.Touched:Connect(function(hit)
        local plr = players:GetPlayerFromCharacter(hit.Parent)
        if plr then
            badgeService:AwardBadge(plr.UserId, id)
        end
    end)