Gear gave to players from a badge earned, which a 1 in 5 chance works (when I start the game)

Hello, I’m DarkBegin and I’m working on a script giving a gear in your backpack if you earned the correct badge from my game.
Actually the script doesn’t work every time…
Firstly, I asked to my friends to fix it, but no one is able to fix it, they say it’s a bug from Roblox. So I’m asking in the dev forum if anyone could help me to fix thank you. :slight_smile:
Here is the script, tidied in ServerScriptService . The gear is in ReplicatedStorage and its name is “SKRAA SWORD”

local BadgeService = game:GetService("BadgeService")

local Players = game:GetService("Players")

local badgeID = 2124536207   -- Change le numero en mettant id du badge

local ReplicateStorage = game:GetService("ReplicatedStorage")

local Gear = ReplicateStorage:WaitForChild("SKRAA SWORD")


Players.PlayerAdded:Connect(function(player)
    local sucess, hasBadge = pcall(function()
        return BadgeService:UserHasBadgeAsync(player.UserId, badgeID)
    end)
    
    if not sucess then
        warn("Il y a une erreur")
        return
    end
    
    if hasBadge then 
        local sword = Gear:Clone()
        sword.Name = "Sword"
        sword.Parent = player.Character 
        print("il a le Gear")
        
    else 
        print("Il na pas le Gear")
    end
end)

Use the player’s backpack. But if you insist on using the Character, then check if the player has one first, if they don’t, wait for it to be loaded.

As for your issue, I think this is the problem:

The function WaitForChild() yields until the sword actually loads in ReplicatedStorage, and sometimes it loads too late to detect the first player that joins. Put it under the function. So now our code looks like this:

local BadgeService = game:GetService("BadgeService")

local Players = game:GetService("Players")

local badgeID = 2124536207   -- Change le numero en mettant id du badge

local ReplicateStorage = game:GetService("ReplicatedStorage")


Players.PlayerAdded:Connect(function(player)
    local Gear = ReplicateStorage:WaitForChild("SKRAA SWORD")
    local sucess, hasBadge = pcall(function()
        return BadgeService:UserHasBadgeAsync(player.UserId, badgeID)
    end)
    
    if not sucess then
        warn("Il y a une erreur")
        return
    end

    if hasBadge then 
        local sword = Gear:Clone()
        sword.Name = "Sword"
        if not player.Character then
            player.CharacterAdded:Wait()
        end
        sword.Parent = player.Character 
        print("il a le Gear")
        
    else 
        print("Il na pas le Gear")
    end
end)

Also, post this in #help-and-feedback:scripting-support next time. This is not the right place to ask for help about scripting. This category is for asking how efficient your code is.

Okay thank you for helping me, I rarely post help requests, so I’ll be careful next time, thank you again ^^

1 Like