I can’t seem to figure out this error. I’m still learning on how to code on Roblox but I don’t get what’s wrong. I used a bit of the DevForum and the Developer Roblox website (I don’t really know what to call it or what most people call it)
But what I’m trying to figure out is when the player get their first kill, they would get the “First Kill” badge.
local BadgeService = game:GetService("BadgeService")
local BadgeID = 000000
game.Players.PlayerAdded:Connect(function(Player)
if Player:WaitForChild("leaderstats").Kills.Value >= 1 then
local success,result = pcall(BadgeService.UserHasBadgeAsync,BadgeService,Player.UserId,BadgeID)
if success then
if not result then
local success2, result2 = pcall(BadgeService.AwardBadge, BadgeService, Player.UserId, BadgeID)
if success2 then
BadgeService:AwardBadge(Player.UserId,BadgeID)
end
end
end
end
end)
When working with such services, it’s always recommended to use pcalls.
From looking at the error, I can assume leaderstats doesn’t exist in the Player object.
You should use :WaitForChild("leaderstats") or :FindFirstChild("leaderstats") if possible, and also, the explorer screenshot is not of help here as it doesn’t show the children of an Player in-game.
Test play your game and screenshot the explorer (more specifically, an Player in the Players service) so we can help you.
Okay so, first of all we should check your error. Since both of those scripts you create leaderstats run at the same time, it wont work.
You can fix this by adding a repeat task.wait() until plr:FindFirstChild("leaderstats") ~= nil
So by now your code should look like this:
local badgeID = --stuff stuff
local badgeService = game:GetService("BadgeService")
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(plr)
repeat task.wait() until plr:FindFirstChild("leaderstats") ~= nil --Wait until leaderstat exists
if plr.leaderstats.Kills.Value >= 1 then
badgeService:AwardBadge(plr.UserId, badgeID)
print("good")
end
end)
Error is fixed, but from your post you want player to be awarded whenever they get the kill, this script you made will only check once, when player joined the game.
You can also use Changed event, to fix this.
local badgeID = --stuff stuff
local badgeService = game:GetService("BadgeService")
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(plr)
repeat task.wait() until plr:FindFirstChild("leaderstats") ~= nil --Wait until leaderstat exists
--First check
if plr.leaderstats.Kills.Value >= 1 then
badgeService:AwardBadge(plr.UserId, badgeID)
print("good")
end
--Checks whenever Kills value is changed
plr.leaderstats.Kills.Changed:Connect(function()
if plr.leaderstats.Kills.Value >= 1 then
badgeService:AwardBadge(plr.UserId, badgeID)
print("good")
end
end)
end)