I have used a tutorial to set up a data store for my data 'Races won', however, whenever I go to try and save the data by making the player leave or waiting and then rejoin the game again, nothing happens and the data is set back to 0. I know this is a lot of code to look through, but it would be greatly appreciated if someone could see if they could figure out what the problem is.
Code:
local PlayerStatManager = {}
local DataStoreService = game:GetService("DataStoreService")
local playerData = DataStoreService:GetDataStore("PlayerData")
local sessionData = {}
local AUTOSAVE_INTERVAL = 60
-- function to save when player joins
local function setupPlayerData(player)
local playerUserId = "Player_" .. player.UserId
local data = playerData:GetAsync(playerUserId)
if data then
sessionData[playerUserId] = data
else
sessionData[playerUserId] = {["Races won"] = 0}
end
end
game.Players.PlayerAdded:Connect(setupPlayerData)
--function to save player's data
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
playerData:SetAsync(playerUserId, sessionData[playerUserId])
end
end
--function to save player's data when they leave
local function saveOnExit(player)
local playerUserId = "Player_" .. player.UserId
savePlayerData(playerUserId)
end
game.Players.PlayerRemoving:Connect(saveOnExit)
--function to auto save
local function autoSave()
while wait(AUTOSAVE_INTERVAL) do
for playerUserId, data in pairs(sessionData) do
savePlayerData(playerUserId)
end
end
end
-- Start running "AutoSave() funciton to "PlayerAdded"
spawn(autoSave)
--Connect "setupPlayerData()" to "PlayerAddded" event
game.Players.PlayerAdded:Connect(setupPlayerData)

5 comments
Wow, I love your style of explaining deep into the code. You got my respect, man!
Never make data store calls ina changed event. You have no control over it and will reach the get/set limits quickly causing issues.
@kingdom, I can make a advanced DataStore, but I prefer this one. Is simple to understand and it doesn't take a lot of time!
I don't understand why you've used a touched event in there, I wanted it to just save the points such as editing my script, not a racing script. Thanks for trying, however.
.-. I saw "Wins" and I tough that was a racing game. Sorry.