So, I trying to create auto-saving stats for players. But, for some reason it always loads at 0. Something like: I close game with "strength 3", but when start game again "strength" will be at 0.
local DSS = game:GetService("DataStoreService")
local MDS = DSS:GetDataStore("MyDataStore")
game.Players.PlayerAdded:Connect(function(player)
local Stats = Instance.new("Folder") --All "stats" with folder.
Stats.Name = "Stats"
Stats.Parent = player
local AGL = Instance.new("IntValue")
AGL.Name = "AGL"
AGL.Parent = Stats
AGL.Value = 1
local STR = Instance.new("IntValue")
STR.Name = "STR"
STR.Parent = Stats
STR.Value = 1
local INT = Instance.new("IntValue")
INT.Name = "INT"
INT.Parent = Stats
INT.Value = 1
local VIT = Instance.new("IntValue")
VIT.Name = "VIT"
VIT.Parent = Stats
VIT.Value = 1
local LOD = Instance.new("IntValue")
LOD.Name = "LAD"
LOD.Parent = Stats
LOD.Value = 1
local LeVeL = Instance.new("IntValue")
LeVeL.Name = "LeVeL"
LeVeL.Parent = Stats
LeVeL.Value = 0
local essenceNeeded = Instance.new("IntValue") --checking data
essenceNeeded.Name = "essenceNeeded"
essenceNeeded.Parent = Stats
essenceNeeded.Value = 1
local data
local success, errormessage = pcall(function()
data = MDS:GetAsync(player.UserId)
end)
if success then
AGL.Value = data[1] --loading data or sending error
INT.Value = data[2]
STR.Value = data[3]
VIT.Value = data[4]
LOD.Value = data[5]
LeVeL.Value = data[6]
essenceNeeded.Value = data[7]
print("Data loaded")
else
print("Not success")
warn(errormessage)
end
end)
game.Players.PlayerRemoving:Connect(function(player) --saving data
local function create_table(player)
local player_stats = {}
for _, stat in pairs(player.Stats:GetChildren()) do
player_stats[stat.Name] = stat.Value
end
return player_stats
end
local success, errormessage = pcall(function()
local player_stats = create_table(player)
local playerUserId = "Player_" .. player.UserId
MDS:SetAsync(playerUserId, player_stats)
end)
if success then
print("Data saved")
else
print("Fail")
warn(errormessage)
end
end)
I already tried changing script, or creating new but different. I tried added 'print("1works")' everything goes right.

5 comments
chess123mate, BindToClose helped but then new error shows: "ServerScriptService.statsStorage:67: attempt to index nil with 'Stats'"
I assume you've changed your code somehow because 'player' should be defined on line 67. I would print out 'player' at various parts of your code (in the PlayerRemoving function) to make sure that it exists and figure out how it becomes nil.
Probably because I changed "64: game.Players.PlayerRemoving:Connect(function(player)" to "64: game.BindToClose:Connect(function(player)".
I've edited the answer to clarify
chess123mate, really thanks for help. I would never correct that without help.