Leaderstats Error by Script (Gui)

I have an error that prevents me from receiving such an item. When I click on the gui button, I should get the item if I had the rank I wanted, when I tested it with the right rank, an error appears. Can you help me?

Players.OmqFroko.PlayerGui.BSMShop.Shop.Tango.Recruta:6: attempt to index nil with 'leaderstats'
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local button = script.Parent

script.Parent.MouseButton1Click:Connect(function(player)
	if player.leaderstats.Rank.Value == "R| Recruta" then

		local ToolGiver = ReplicatedStorage.ShopItems.Tango:Clone()
		ToolGiver.Parent = player.Backpack

		local ToolGiver = ReplicatedStorage.ShopItems.Tango:Clone()
		ToolGiver.Parent = player.StarterGear
	end
end)

leaderstats doesn’t exist upon calling the event.
Double-check if they have leaderstats first.

local Stats = Player:FindFirstChild('leaderstats')
if (Stats) then
   ---
end

@Xacima pretty much covered it, but the way you are locating the rank in the first place isn’t ideal.

You can use

local rank = player:GetRoleInGroup(GROUPID)

if rank == "R| Recruta" then
--// code
end

Why? That way if leaderstats for some reason doesn’t work, you still can run this code properly, and it’s also better practice imo, and lets you manage your code better.

I don’t have a Roblox group so I’m using the “Rank” from the leaderstats.

Ah alright, gotcha. That makes sense then.

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local button = script.Parent

local player = game:GetService("Players").LocalPlayer

script.Parent.MouseButton1Click:Connect(function()
	if player.leaderstats.Rank.Value == "R| Recruta" then

		local ToolGiver = ReplicatedStorage.ShopItems.Tango:Clone()
		ToolGiver.Parent = player.Backpack

		local ToolGiver = ReplicatedStorage.ShopItems.Tango:Clone()
		ToolGiver.Parent = player.StarterGear
	end
end)

this will work idk if that works the problem was leaderstats cannot found but im changing the player or maybe u need to sure if the name of ur leaderstats is leaderstats

It worked, the problem is that I had to change the “script” to “LocalScript” but that’s no problem. Thanks

You should be handling the player’s gui with local scripts anyway.