Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Auto-Save Data Store Coming Out With Error: attempt to index nil with 'leaderstats'?

I am trying to expand my scripting knowledge with what I see as the most important part of a game, data stores. I have watched video after video, article after article and still come out with errors, help would be greatly appreciated.

Code:

local DataStoreService = game:GetService('DataStoreService')
local DataSave = DataStoreService:GetDataStore('SaveData')

game.Players.PlayerAdded:Connect(function(player)
	local Leaderstats = Instance.new('Folder')
	Leaderstats.Name = 'leaderstats'
	Leaderstats.Parent = player
	
	local Cash = Instance.new('IntValue')
	Cash.Name = 'Cash'
	Cash.Parent = Leaderstats
	
	local data
	local playerID = player.UserId
	
	local success, errmessage = pcall(function()
		data = DataSave:GetAsync(playerID..'-Cash')
	end)
	
	if success then
		Cash.Value = data
	else
		warn(errmessage)
	end
end)

while wait(30) do
	for number, player in pairs(game.Players:GetChildren()) do
		local playerID = player.UserId
		local success, errormessage = pcall(function(player)
			DataSave:SetAsync(playerID..'-Cash', player.leaderstats.Cash.Value)
		end)
	
		if success then
			print("Succes!")
		else
			warn(errormessage)
		end
	end
end 
  • wolftamer894

1 answer

✓ Accepted answer
local success, errormessage = pcall(function(player) -- try removing player from this and making it local success, errormessage = pcall(function() 
	DataSave:SetAsync(playerID..'-Cash', player.leaderstats.Cash.Value)
end)

also might want to use game.Players:GetPlayers()

1 comment

0

Thank You So Much!

This discussion is preserved as it was. New answers, comments, and votes are closed.