Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Set up table to return to any script that requires this module script
- local CarStatManager = {}
- local DataStoreService = game:GetService("DataStoreService")
- local carData = DataStoreService:GetDataStore("carData")
- -- Table to hold player information for the current session
- local sessionData = {}
- -- Function that other scripts can call to change a player's stats
- function CarStatManager: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
- else
- sessionData[playerUserId][statName] = value
- end
- end
- function CarStatManager:GetStat(player)
- -- local success, currentExperience = pcall(function()
- -- return carData:GetAsync("Player_"..player.UserId)
- -- end)
- return sessionData[player.UserId]["Owned"]
- end
- -- Function to add player to the 'sessionData' table
- local function setupPlayerData(player)
- local playerUserId = "Player_" .. player.UserId
- local success, data = pcall(function()
- return carData:GetAsync(playerUserId)
- end)
- if success then
- if data then
- warn(player.Name.." Is in car database.")
- warn("Fetching data for player: "..player.Name)
- -- Data exists for this player
- sessionData[playerUserId] = data
- else
- warn(player.Name.." Haven't played before")
- warn("Setting Default Values for Player: "..player.Name)
- -- Data store is working, but no current data for this player
- sessionData[playerUserId] = {
- ["Owned"] = {}
- }
- end
- else
- warn("Error: Couldn't fetch Car Data")
- end
- end
- -- Function to save player's data
- local function saveCarData(playerUserId)
- if sessionData[playerUserId] then
- carData:SetAsync(playerUserId, sessionData[playerUserId])
- end
- end
- -- Function to save player data on exit
- local function saveOnExit(player)
- local playerUserId = "Player_" .. player.UserId
- saveCarData(playerUserId)
- end
- -- Connect 'setupPlayerData()' function to 'PlayerAdded' event
- game.Players.PlayerAdded:Connect(setupPlayerData)
- -- Connect 'saveOnExit()' function to 'PlayerRemoving' event
- game.Players.PlayerRemoving:Connect(saveOnExit)
- return CarStatManager
Advertisement
Add Comment
Please, Sign In to add comment