How do I find the value from the leaderstats?

Hi there. I’m just trying to script something for a personal project, and it says this error message ServerScriptService.Make shit happen:21: attempt to index nil with ‘FindFirstChild’ - Server for just trying to get a value called Lions that is one of the main currencies for the game.
I will share the part that sends this message:

game.Players.PlayerAdded:Connect(function(player)
	local leaderstats  = player:FindFirstChild("leaderstats")
	local Changeng = leaderstats:FindFirstChild("Lions").Value
	print(Changing + 1)
end)
1 Like
--!strict

local Players = game:GetService("Players")

local LEADERSTATS_FOLDER_NAME = "leaderstats"

Players.PlayerAdded:Connect(function(player)
	local function onLeaderstatsAdd(leaderstats: Folder)
		local lionsValue = (leaderstats:FindFirstChild("Lions") :: unknown) :: IntValue?
		if not lionsValue then
			return
		end
		
		local lions = lionsValue.Value
		print(lions + 1)
	end

	local leaderstats = player:FindFirstChild(LEADERSTATS_FOLDER_NAME)
	if leaderstats then
		onLeaderstatsAdd(leaderstats)
	end
	
	player.ChildAdded:Connect(function(child)
		if child.Name ~= LEADERSTATS_FOLDER_NAME then
			return
		end
		
		onLeaderstatsAdd(child)
	end)
end)
1 Like

pretty clear right there that it’s finding the Changing value but the var name is Changeng

also it’s better to use if statement before accessing that object, FindFirstChild doesn’t always prevent errors if the object that uses findfirstchild on top hasn’t been loaded.

1 Like

Two problems:

  1. ServerScriptService.Make shit happen:21: attempt to index nil with ‘FindFirstChild’ - Server
    This means that you are trying to call the FindFirstChild method on a variable that has a value of nil. I assume that the nil indexing is happening on leaderstats:FindFirstChild("Lions").Value, meaning that leaderstats is nil. This could happen because of the leaderstats folder instance hasn’t been created yet or it doesn’t exist. Make sure you are creating a leaderstats folder inside the player. If you are, try using the WaitForChild method instead.

  2. You are setting a variable named Changeng equal to the desired leaderstats value, however you later try to print Changing + 1, you’ll need to fix those references.

2 Likes

Thank you for helping me out!1!!!1!!!1

2 Likes