Hello. I have big problem with my savedata. I wiped out my saves in studio while i started and stopped game quick. Then some error like “Player didnt loaded because left server bla bla”
And then I started again i realized my savedata was at state like at first join.
local DataStoreService=game:GetService("DataStoreService")
local datasave = DataStoreService:GetDataStore("data")
Players.PlayerAdded:Connect(function(player)
local data = require(pathtomodule)
local playerdata = nil
local success, playerdata = pcall(function()
return datasave:GetAsync(player.UserId)
end)
if not playerdata then
playerdata = {
stuff = 0,
}
local success, errmsg = pcall(function()
datasave:SetAsync(player.UserId, playerdata)
end)
end
data.stuff=playerdata.stuff --first i copy playerdata to module in serverscript
end)
Players.PlayerRemoving:Connect(PlayerLeaving)(
local data = require(pathtomodule)
local playerdata = {
stuff=data.stuff
}
local sucess , errormsg = pcall(function()
datasave:SetAsync(player.UserId, playerdata)
end)
end)
you should only save data after you validate its already been loaded, you can use attribute on a player to easily do this
local DataStoreService=game:GetService("DataStoreService")
local datasave = DataStoreService:GetDataStore("data")
Players.PlayerAdded:Connect(function(player)
local data = require(pathtomodule)
local playerdata = nil
local success, playerdata = pcall(function()
return datasave:GetAsync(player.UserId)
end)
if not playerdata then
playerdata = {
stuff = 0,
}
local success, errmsg = pcall(function()
datasave:SetAsync(player.UserId, playerdata)
end)
end
data.stuff=playerdata.stuff --first i copy playerdata to module in serverscript
player:SetAttribute('DataLoaded', true)
end)
Players.PlayerRemoving:Connect(PlayerLeaving)(
if PlayerLeaving:GetAttribute('DataLoaded') then
local data = require(pathtomodule)
local playerdata = {
stuff=data.stuff
}
local sucess , errormsg = pcall(function()
datasave:SetAsync(player.UserId, playerdata)
end)
end
end)