Advertisement
1m1m0

Basic Leaderstats Data Saving

Jan 1st, 2024
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.54 KB | None | 0 0
  1. -- Requires Basic Leaderstats --
  2.  
  3. local DataStoreService = game:GetService("DataStoreService")
  4. local playerDataStore = DataStoreService:GetDataStore("PlayerData")
  5.  
  6. local function savePlayerData(player)
  7.     local key = "player-" .. player.UserId
  8.  
  9.     local data = {                              -- Stat data to be saved, to change it, make sure to change the names to the desired stat.
  10.         coins = player.leaderstats.Coins.Value, -- For example, To change this to Cash, change it to "cash = player.leaderstats.Cash.Value"
  11.         kills = player.leaderstats.Kills.Value,
  12.         deaths = player.leaderstats.Deaths.Value,
  13.         level = player.leaderstats.Level.Value,
  14.         xp = player.leaderstats.XP.Value
  15.     }
  16.  
  17.     playerDataStore:SetAsync(key, data)
  18. end
  19.  
  20. local function loadPlayerData(player)
  21.     local key = "player-" .. player.UserId
  22.  
  23.     local success, data = pcall(function()
  24.         return playerDataStore:GetAsync(key)
  25.     end)
  26.  
  27.     if success and data then                            -- Apply the same logic as the one above.
  28.         player.leaderstats.Coins.Value = data.coins     -- If you want to change it to cash, change it to "player.leaderstats.Cash.Value = data.cash". Then it will save/load it properly.
  29.         player.leaderstats.Kills.Value = data.kills
  30.         player.leaderstats.Deaths.Value = data.deaths
  31.         player.leaderstats.Level.Value = data.level
  32.         player.leaderstats.XP.Value = data.xp
  33.     end
  34. end
  35.  
  36. game.Players.PlayerAdded:Connect(function(player)
  37.     player.CharacterAdded:Connect(function(character)
  38.         loadPlayerData(player)
  39.     end)
  40.  
  41.     player.CharacterRemoving:Connect(function(character)
  42.         savePlayerData(player)
  43.     end)
  44. end)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement