The expected result of the SaveData() function in the code below is to print "Saved data for Player1." However, it NEVER prints this. I'm having trouble because this also occurs when I replace UpdateAsync() with SetAsync(). No error is returned either.
Here's the whole script:
local DataManager = {} local DataStoreService = game:GetService("DataStoreService") local PlayerData = DataStoreService:GetDataStore("PlayerData") local SessionData = {} -- Current game data local StartingData = -- Data for players who have never played. { Cash = 0, Experience = 0, Level = 0, TotalDamage = 0, EquippedWeapon = "Stick", Weapons = {"Stick"} } local function SaveData(Player) local PlayerId = Player.UserId local Data = SessionData[PlayerId] print(Player.Name .. " left. Saving data.") if Data then local success, err = pcall(function() PlayerData:UpdateAsync(PlayerId, function(old) return Data end) end) if not success then print(err) error("Cannot save data for " .. Player.Name .. "!") end end print("Saved data for " .. Player.Name .. ".") end game.Players.PlayerRemoving:Connect(function(Player) SaveData(Player) end) return DataManager
There is a simpler way of doing it... Here: (Hope it helps!!)
local Service = game:GetService('DataStoreService'):GetDataStore('CHANGE_THIS')--Change whats inside the '' not the variable game.Players.PlayerAdded:connect(function(plr) local stats = plr:WaitForChild('leaderstats') local Exp = stats:WaitForChild('Exp')--Change whats inside the '' not the variable local Level = stats:WaitForChild('Level')--Change whats inside the '' not the variable local uniquekey = 'id-'..plr.userId local GetSaved = Service:GetAsync(uniquekey) if GetSaved then Exp.Value = GetSaved[1] Level.Value = GetSaved[2] else local SavingNums = {Exp.Value,Level.Value} Service:SetAsync(uniquekey,SavingNums) end end) game.Players.PlayerRemoving:connect(function(plr) local stats = plr:WaitForChild('leaderstats') local Exp = stats:WaitForChild('Exp')--Change whats inside the '' not the variable local Level = stats:WaitForChild('Level')--Change whats inside the '' not the variable local uniquekey = 'id-'..plr.userId local Savetable = {Exp.Value,Level.Value} Service:SetAsync(uniquekey,Savetable) end)--Hope this helps you out!
Enjoy.