When I load in, and change my data and leave, it prints saying that it’s saving the new data amount. But when I re-join it reverts back to the default amount?
local DefaultData = {
Cash = 500,
PurchasedItems = {}
}
local StoredData = {} -- Stored data for all players
--// Load player data on join
function DataManager.Load(player)
-- Create leaderstats and data
local Leaderstats = Instance.new("Folder")
Leaderstats.Name = "leaderstats"
local Cash = Instance.new("IntValue")
Cash.Name = "Cash"
Leaderstats.Parent = player
Cash.Parent = Leaderstats
-- Get saved data
local Data
local Success, Error = pcall(function()
print(DataStore:GetAsync(player.UserId).Cash) -- Prints '500'
Data = DataStore:GetAsync(player.UserId) or DefaultData
end)
if Success then -- Data loaded
Cash.Value = Data.Cash -- Set cash value
else -- Data did not load
warn(Error)
player:Kick("Your data failed to load: " .. Error)
end
StoredData[player] = Data -- Save the players data to a global table
--// Update StoredData when cash changes
Cash:GetPropertyChangedSignal("Value"):Connect(function()
StoredData[player].Cash = Cash.Value
end)
end
--// Save player data on leave
function DataManager.Save(player)
local Success, Error = pcall(function()
print("Saving", StoredData[player].Cash) -- Prints 'Saving 100000'
DataStore:SetAsync(player.UserId, StoredData[player])
end)
if not Success then -- Data did not save
warn(Error)
end
StoredData[player] = nil -- Clear data from global table
end