Attempt to index nil with 'Cash' [Leaderstats]

  1. What do you want to achieve? Keep it simple and clear!

I need the data to be saved, but I can’t figure out what the problem is.

  1. What is the issue? Include screenshots / videos if possible!

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    -nothing
game.Players.PlayerAdded:Connect(function(plr)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = plr
	
	local coins = Instance.new("IntValue")
	coins.Name = "Cash"
	coins.Parent = leaderstats
	
	local success, res = pcall(function()
		return myData:GetAsync(plr.UserId.."-data")
	end)
	
	if success then
		coins.Value = res.Cash -- 31 Line. Error Here.,
	else
		warn(res)
	end
	
	while wait(5) do
		if not plr then
			break
		end
		
		coins.Value += math.random(1,5)
	end
end)
1 Like

you didn’t verify that the player possessed Data IMO, ou should just set a default value ( probably 0 ) as it will be initialized once the player leaves and you save their data.

the reason it passes the Pcall is that it doesn’t not make an error, it just returns nil…

???

function SaveData(player)
	local success, err = pcall(function()
		myData:SetAsync(player.UserId.."-data", {coins = player.leaderstats.Cash.Value})
	end)
	
	if not success then
		warn(err)
	end
end
1 Like

I still can’t figure out where I made a mistake

1 Like

When a player enter your game for the first time, he doesn’t have any entry in the datastore, In Studio when you press PLAY or F5, it simulate the Data of a FIRST time visit on your game. Hence why it returns nil

EDIT : to be more precise, you just need to see if there’s an entry… if yes use Data, if not use default value simple enough right ?

1 Like

It’s

coins.Value = res.coins

since in your data saving, you saved it as coins and not Cash

I’ve already tried to do this. It doesn’t work(

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.