What is the best way to get a players leaderstat?

I am trying to make a portal where if the player has enough Levels they can enter it. I’m getting a few errors when trying it and not sure if I’m getting the player’s leaderstats correctly.

Errors: leaderstats is not a valid member of Part, Attempt to index nil ‘WaitForChild’, and Attempt to index nil ‘FindFirstChilld’.

Example Script:

local function hasLevels(player)
	local leaderstats = player:FindFirstChild("leaderstats")
	local Level = player.leaderstats:WaitForChild("Level")

	if leaderstats.Level.Value >= 1 then
		print("Player has access to area")
	end
end
2 Likes

You are checking the leaderstat value correctly, the problem most likely has to do with the player parameter in your function, as it is calling it a part on the error message.

If this function is called by a Touched event, you have to reference the Player instead by getting the Player’s Character using the GetPlayerFromCharacter function which requires a Character Model

If I use GetPlayerFromCharacter could I use (player) from the function and use it inside of the GetPlayerFromCharacter? Or would I have to create another variable for it

Pretty much, the function is pretty straight-forward on how it’s called: You need a Player Character to detect so we’d need to get the HitPart’s Parent in this Instance

You can create a Player variable when you fire the function, checking if it’s a valid Player or not:

local function hasLevels(HitPart)
    local Player = game.Players:GetPlayerFromCharacter(HitPart.Parent)

	if Player then	   
        if Player.leaderstats.Level.Value >= 1 then
		    print("Player has access to area")
        end
	end
end
2 Likes

You have to write a variable, here’s an example.
I would suggest using hierarchy for your purpose.

local BasePart = script:FindFirstAncestorWhichIsA("BasePart")

local function OnTouched(HitInstance)
	local Character = HitInstance:FindFirstAncestorWhichIsA("Model")
	local Humanoid = Character:FindFirstChildWhichIsA("Humanoid")
	local Player = game:GetService("Players"):GetPlayerFromCharacter(Character)

	if Player:FindFirstChild("leaderstats")["Level"] >= 1 then
		print("Player has access to arena.")
	end
end

BasePart.Touched:Connect(OnTouched)

Would the Player already have a leaderstat in it so I wouldn’t have to make a leaderstat variable with the player?

If the conditional checks are met, and you’ve already created the leaderstats in another script then yes since it’ll only fire when the Part is Touched

Variables are just for an easier approach defining everything right, but I just chose a lazy way to do it so ¯_(ツ)_/¯

Alright thank you helping me learn this a bit better

1 Like