Help with this script that checks if a person has a badge and gives them a trail when they press a button

Hello develops, would you mind helping me. I have spent hours trying to work this code and this is my last resort.

what is the script about?
I have made a trail menu and you get this trail when you get a certain badge.

local BadgeService = game:GetService("BadgeService")
local Players = game:GetService("Players")

local badgeID = 2124666454 

local function onPlayerAdded(player)
	-- Check if the player has the badge
	local success, hasBadge = pcall(function()
		return BadgeService:UserHasBadgeAsync(player.UserId, badgeID)
	end)

	-- If there's an error, issue a warning and exit the function
	if not success then
		warn("Error while checking if player has badge!")
		return
	end

	if hasBadge then
		script.Parent.MouseButton1Click:Connect(function()
			game.ReplicatedStorage.CloneTrail:FireServer(script.Parent.Name)	
		end)
	end
end

-- Connect "PlayerAdded" events to the "onPlayerAdded()" function
Players.PlayerAdded:Connect(onPlayerAdded)

useful information
There are no errors on the output window.
I got the script from the developer hub as it is very useful

Here is the script for equipping a trail without a badge (which works):

local Players = game:GetService("Players")

local player = Players.LocalPlayer


script.Parent.MouseButton1Click:Connect(function()
		game.ReplicatedStorage.CloneTrail:FireServer(script.Parent.Name)	
	end)

This is a script that gives a trail if the person is my group (also works)

local groupId = 3447607
local Players = game:GetService("Players")

local player = Players.LocalPlayer


if player:IsInGroup(groupId) then
script.Parent.MouseButton1Click:Connect(function()
		game.ReplicatedStorage.CloneTrail:FireServer(script.Parent.Name)	
	end)
end

Thanks so much in advance any help or advice will be gratefully appreciated :grinning:

Is the first script in a LocalScript?

1 Like

Yes all the codes are located in local scripts and their parent is a text button

Replace the above script with this one:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local BadgeService = game:GetService("BadgeService")
local Players = game:GetService("Players")
Player = Players.LocalPlayer
local badgeID = 2124666454

local success, hasBadge = pcall(function()
    return BadgeService:UserHasBadgeAsync(Player.UserId, badgeID)
end)
if success and hasBadge then
    print(Player.Name, "has this Badge, id:", badgeID)
elseif success and not hasBadge then
    warn(Player.Name, "does not has this Badge, id:", badgeID)
elseif not success then
    warn("Error while checking if player has badge!")
end

script.Parent.MouseButton1Click:Connect(function()
    if hasBadge then
        ReplicatedStorage.CloneTrail:FireServer(script.Parent.Name)
    end
end)
2 Likes

It worked Thank you so much have an amazing day :smile:

1 Like

You’re welcome, happy to help ^ - ^

1 Like