PheonixStudio

Saving Multiple Stats at once

Apr 17th, 2020
570
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.48 KB | None | 0 0
  1. --// Services
  2. local ds = game:GetService("DataStoreService"):GetDataStore("TutorialDataMultipleStats")
  3.  
  4.  
  5. --// Functions
  6. game.Players.PlayerAdded:Connect(function(plr)
  7.     local Prefix = plr.UserId
  8.    
  9.     local leaderstats = Instance.new("Folder", plr)
  10.     leaderstats.Name = "leaderstats"
  11.    
  12.     local Cash = Instance.new("IntValue", leaderstats)
  13.     Cash.Name = "Cash"
  14.     local Gems = Instance.new("IntValue", leaderstats)
  15.     Gems.Name = "Gems"
  16.    
  17.     local Data = nil -- This will return Nill if a table wasn't found within the Saved Data.
  18.    
  19.     pcall(function()
  20.         Data = ds:GetAsync(Prefix) -- grabs the saved table and inserts them into the Variable Data
  21.     end)
  22.        
  23.     if Data ~= nil then -- If there IS data available then
  24.         for i,v in pairs(leaderstats:GetChildren()) do -- loops and loads data
  25.             v.Value = Data[v.Name]
  26.         end
  27.     else -- else no data available then we create start values
  28.         Cash.Value = 200
  29.         Gems.Value = 0
  30.     end
  31. end)
  32.  
  33. game.Players.PlayerRemoving:Connect(function(plr)
  34.     local Prefix = plr.UserId
  35.    
  36.     local leaderstats = plr.leaderstats -- Finds the Folder
  37.    
  38.     pcall(function()
  39.         if leaderstats then
  40.             local SaveData = {} -- This table will contain our desired stats to save
  41.             -- Order would look like:
  42.             -- ["Cash"] = 275
  43.             -- ["Gems"] = 100
  44.            
  45.             for i,v in pairs(leaderstats:GetChildren()) do -- Again loops and finds / saves the data within a table
  46.                 SaveData[v.Name] = v.Value
  47.             end
  48.            
  49.             ds:SetAsync(Prefix, SaveData) -- Saves the data in the SaveData
  50.         end
  51.     end)
  52. end)
Advertisement
Add Comment
Please, Sign In to add comment