Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local PlayerStatManager = {}
- local DataStoreService = game:GetService('DataStoreService')
- local playerData = DataStoreService:GetDataStore('PlayerData')
- local AUTOSAVE_INTERVAL = 60
- local DATASTORE_RETRIES = 3
- local sessionData = {}
- function PlayerStatManager:ChangeStat(player, statName, changeValue)
- sessionData[player][statName] = sessionData[player][statName] + changeValue
- end
- local function dataStoreRetry(dataStoreFunction)
- local tries = 0
- local success = true
- local data = nil
- repeat
- tries = tries + 1
- success = pcall(function() data = dataStoreFunction() end)
- if not success then wait(1) end
- until tries == DATASTORE_RETRIES or success
- if not success then
- error('Could not access DataStore! Warn players that their data might not get saved!')
- end
- return success, data
- end
- local function getPlayerData(player)
- return dataStoreRetry(function()
- return playerData:GetAsync(player.UserId)
- end)
- end
- local function savePlayerData(player)
- if sessionData[player] then
- return dataStoreRetry(function()
- return playerData:SetAsync(player.UserId, sessionData[player])
- end)
- end
- end
- local function setupPlayerData(player)
- local success, data = getPlayerData(player)
- if not success then
- sessionData[player] = false
- else
- if not data then
- sessionData[player] = {Money = 0, Experience = 0}
- savePlayerData(player)
- else
- sessionData[player] = data
- end
- end
- end
- local function autosave()
- while wait(AUTOSAVE_INTERVAL) do
- for player, data in pairs(sessionData) do
- savePlayerData(player)
- end
- end
- end
- game.Players.PlayerAdded:connect(setupPlayerData)
- game.Players.PlayerRemoving:connect(function(player)
- savePlayerData(player)
- sessionData[player] = nil
- end)
- spawn(autosave)
- return PlayerStatManager
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement