Help with finding leaderstats value in ServerScriptService

Hey I have worked a lot on this script and finally, when it did work it only works 50 percent of the time so this script gives you +1 Cash if you touch “Gems” but sometimes it gives the error: attempt to index nil with “Cash” and I don’t understand

  1. What do you want to achieve? Keep it simple and clear!
    That it always can detect the Cash value and not give the index nil error because when i touch the “Gems” it gives the error attempt to index nil with ‘Value’

  2. What is the issue? Include screenshots / videos if possible!
    Here is my script

So what exactly is the problem? Can you provide an error of somesort?

When you have a problem, break it into pseudo-code first. What does this do? Simple.

When Player joins the game, index global variable ‘cash’ with the player’s leaderstats.
When Gem is touched, increase cash value by 1. Why doesn’t this work? Because, only one player is
indexed with ‘cash’. The first player who joins. So, if this player leaves, the script errors.To fix this, don’t contain a variable of “cash”, instead, use player:FindFirstChild(“leaderstats”).Cash I also see another issue, I don’t see the “Cash” variable or “leaderstats” folder created in the PlayerAdded connection.


Hello, it is possible that your script loads before instance cash is created, so you have to do

local leaderstats = player:WaitForChild("leaderstats")
1 Like

Well, you’re not finding the humanoid the correct way for one, and you’re not getting the player’s cash correctly either.

function onTouch(hit)
	local model = hit:FindFirstAncestorWhichIsA("Model") -- finds the character model more efficiently than using .Parent
	if model then
		local humanoid = model:FindFirstChildWhichIsA("Humanoid")
		if humanoid then
			local player = Players:GetPlayerFromCharacter(model)
			if player then
				local leaderstats = player:FindFirstChild("leaderstats")
				if leaderstats then
					leaderstats.Cash.Value += 1
1 Like