I followed the official roblox Save Player Data Article ( https://developer.roblox.com/en-us/articles/Saving-Player-Data ) but for some reason it doesn’t work. I don’t get any errors. I’ve tried with prints and it confirms that the data is saved but when I join back it doesn’t see any saved data
local PlayerStatManager = {}
local DataStoreService = game:GetService("DataStoreService")
local playerData = DataStoreService:GetDataStore("playerData")
local sessionData = {}
local AUTOSAVE_INTERVAL = 60
function PlayerStatManager:ChangeStat(player,statName,value)
local playerUserId = "Player_"..player.UserId
assert(typeof(sessionData[playerUserId][statName]) == typeof(value), "ChangeStat error: types do not match")
if typeof(sessionData[playerUserId][statName]) == "number" then
sessionData[playerUserId][statName] = sessionData[playerUserId][statName] + value
print(statName.." Value Added")
else
sessionData[playerUserId][statName] = value
print("Value = Value")
end
end
local function setupPlayerData(player)
local playerUserId = "Player_"..player.UserId
local success, data = pcall(function()
local data = playerData:GetAsync(playerUserId)
end)
if success then
if data then -- it says here that there is no data
sessionData[playerUserId] = data
print("Data Found")
else
sessionData[playerUserId] = {Coins=0, Stages=0, Level=0, Rebirths=0, Areas=1, Exp=0, MaxExp=10}
print("No Data Found")
end
else
warn("Cannot save data for player!")
end
end
local function savePlayerData(playerUserId)
if sessionData[playerUserId] then
local tries = 0
local success
repeat
tries = tries + 1
success = pcall(function()
playerData:SetAsync(playerUserId, sessionData[playerUserId])
end)
if not success then wait(1) end
until tries == 3 or success
if not success then
warn("Cannot save data for player!")
end
end
end
local function saveOnExit(player)
local playerUserId = "Player_"..player.UserId
savePlayerData(playerUserId)
end
local function autoSave()
while wait(AUTOSAVE_INTERVAL) do
for playerUserId, data in pairs(sessionData) do
savePlayerData(playerUserId)
end
end
end
spawn(autoSave)
game.Players.PlayerAdded:Connect(setupPlayerData)
game.Players.PlayerRemoving:Connect(saveOnExit)
return PlayerStatManager
I still don’t get why the playeradded worked fine. Everytime a player joined the code ran
edit: and it doesn’t work it keeps saying there is an error while loading the requested module script