This is a part of a script on Roblox wiki, Saving Player Data. I've tried altering it in all sorts of ways but i just can't figure anything out. I've made an obby and a leaderboard that tracks 2 things.The level you've reached and a number of trophies you've collected, and that's the information that's i need saved when a player leaves(i also need it to teleport the player to a checkpoint of a level,based on this info, but i'd be happy with just getting it to remember the numbers) Most of the script is already done i just don't understand what variables i need to add to make it work for my game.
Thanks for your time
-- Setup table that we will return to scripts that require the ModuleScript.
local PlayerStatManager = {}
-- Create variable for the DataStore.
local DataStoreService = game:GetService('DataStoreService')
local playerData = DataStoreService:GetDataStore('Mobbystats')
-- Table to hold all of the player information for the current session.
local sessionData = {}
-- Function the other scripts in our game can call to change a player's stats. This
-- function is stored in the returned table so external scripts can use it.
function PlayerStatManager:ChangeStat(player, statName, changeValue)
sessionData[player][statName] = sessionData[player][statName] + changeValue
end
-- Function to retry the passed in function several times. If the passed in function
-- is unable to be run then this function returns false and creates an error.
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
-- Function to retrieve player's data from the DataStore.
local function getPlayerData(player)
return dataStoreRetry(function()
return playerData:GetAsync(player.UserId)
end)
end
-- Function to save player's data to the DataStore.
local function savePlayerData(player)
if sessionData[player] then
return dataStoreRetry(function()
return playerData:SetAsync(player.UserId, sessionData[player])
end)
end
end
-- Function to add player to the sessionData table. First check if the player has
-- data in the DataStore. If so, we'll use that. If not, we'll add the player to
-- the DataStore.
local function setupPlayerData(player)
local success, data = getPlayerData(player)
if not success then
-- Could not access DataStore, set session data for player to false.
sessionData[player] = false
else
if not data then
-- DataStores are working, but no data for this player
sessionData[player] = {Stage = 1, TrophiesFound = 0}
savePlayerData(player)
else
-- DataStores are working and we got data for this player
sessionData[player] = data
end
end
end
