Here is the code:
local dataStore = game:GetService("DataStoreService") local levelData = dataStore:GetDataStore("LevelSaveSystem") local xpData = dataStore:GetDataStore("XPSaveSystem") local goldData = dataStore:GetDataStore("GoldSaveSystem") game.Players.PlayerAdded:connect(function(player) local leaderstats = Instance.new("Folder", player) leaderstats.Name = "leaderstats" local level = Instance.new("IntValue", leaderstats) level.Name = "Level" local XP = Instance.new("IntValue", leaderstats) XP.Name = "XP" local gold = Instance.new("IntValue", leaderstats) gold.Name = "Gold" local userLevel local userXP local userGold local success, err = pcall(function() userLevel = levelData:GetAsync(player.UserId) or 1 userXP = xpData:GetAsync(player.UserId) userGold = goldData:GetAsync(player.UserId) end) if success then if userLevel and userXP and userGold then wait() level.Value = userLevel XP.Value = userXP gold.Value = userGold end elseif err then player:Kick("Save Data not loaded, please try rejoining.") end print(err) game.Players.PlayerRemoving:connect(function(player) local currentLevel = level.Value local currentXP = XP.Value local currentGold = gold.Value local success, err = pcall(function() levelData:SetAsync(player.UserId, currentLevel) xpData:SetAsync(player.UserId, currentXP) goldData:SetAsync(player.UserId, currentGold) end) if success then print("Data Successfully Saved for user "..player.UserId) end if err then print("There was an error in saving data!") warn(err) end end) end)
PlayerRemoving event as datastore saving is unreliable when the last player leaves (without game:BindToClose()). especially when u test it out in studio
playerRemoving doesnt work in the following conditions: - The last player leaves - The developer manually shut them down via the game page - A network error is encountered and the server is forced to shut down
see this article how to properly save
also test it in game