Why this is not working (datasave)

local players = game:GetService(“Players”)
local dataStoreService = game:GetService(“DataStoreService”)

local saveDataStore = dataStoreService:GetDataStore(“StatsForTutorial”)

players.PlayerAdded:Connect(function(plr)

local stats = Instance.new("Folder")
stats.Name = "leaderstats"
stats.Parent = plr

local money = Instance.new("IntValue")
money.Name = "Money"
money.Parent = stats


local data = saveDataStore:GetAsync(plr.UserId)

if data then
	
	for name,value in pairs(data.Stats) do
		
		stats[name].Value = value
		
	end
end

end)

players.PlayerRemoving:Connect(function(plr)

local saveData = {Stats = {}}

for _,stat in pairs(plr.leaderstats:GetChildren()) do
	
	saveData.Stats[stat.Name] = stat.Value
	
end

saveDataStore:SetAsync(plr.UserId.saveData)

end)

game:BindToClose(function()

for _,plr in pairs(players:GetPlayers()) do
	
	local saveData = {Stats = {}}
	
	for _,stat in pairs(plr.leaderstats:GetChildren()) do
		
		saveData.Stats[stat.Name] = stat.Value
		
	end
	
	saveDataStore:SetAsync(plr.UserId,saveData)
	
end

wait(2)

end)

Error: [ServerScriptService.saving:39: attempt to index field ‘UserId’ (a number value)]

You meant to use a comma instead of a period.

plr.UserId, saveData

Also a potential issue with your bind to close, is it saves each player’s data synchronously instead of asynchronously. I made a tutorial on this.

1 Like