HowToRoblox

SavingScript

Oct 18th, 2019
4,374
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.77 KB | None | 0 0
  1. local Players = game:GetService("Players")
  2. local DataStoreService = game:GetService("DataStoreService")
  3. local SaveDataStore = DataStoreService:GetDataStore("SaveData")
  4.  
  5.  
  6. local function SavePlayerData(player)
  7.    
  8.     local success,errormsg = pcall(function()
  9.    
  10.         local SaveData = {}
  11.        
  12.         for i,stats in pairs(player.leaderstats:GetChildren()) do
  13.            
  14.             SaveData[stats.Name] = stats.Value
  15.         end
  16.         SaveDataStore:SetAsync(player.UserId,SaveData)
  17.     end)
  18.    
  19.     if not success then
  20.         return errormsg
  21.     end        
  22. end
  23.  
  24.  
  25. Players.PlayerAdded:Connect(function(player)
  26.    
  27.     local Stats = Instance.new("Folder")
  28.     Stats.Name = "leaderstats"
  29.     Stats.Parent = player
  30.    
  31.     local Stage = Instance.new("StringValue")
  32.     Stage.Name = "Stage"
  33.     Stage.Parent = Stats
  34.     Stage.Value = 1
  35.    
  36.     local Data = SaveDataStore:GetAsync(player.UserId)
  37.    
  38.     if Data then
  39.            
  40.         print(Data.Stage)
  41.        
  42.         for i,stats in pairs(Stats:GetChildren()) do
  43.            
  44.             stats.Value = Data[stats.Name]     
  45.         end        
  46.     else       
  47.         print(player.Name .. " has no data.")          
  48.     end
  49.    
  50.    
  51.     player.CharacterAdded:Connect(function(character)
  52.        
  53.         local Humanoid = character:WaitForChild("Humanoid")
  54.         local Torso = character:WaitForChild("HumanoidRootPart")
  55.        
  56.         wait()
  57.        
  58.         if Torso and Humanoid then
  59.             if Stage.Value ~= 0 then
  60.                
  61.                 local StagePart = workspace.Stages:FindFirstChild(Stage.Value)
  62.                 Torso.CFrame = StagePart.CFrame + Vector3.new(0,1,0)                   
  63.             end
  64.         end
  65.     end)       
  66. end)
  67.  
  68.  
  69. Players.PlayerRemoving:Connect(function(player)
  70.    
  71.     local errormsg = SavePlayerData(player)
  72.    
  73.     if errormsg then   
  74.         warn(errormsg)     
  75.     end
  76. end)
  77.  
  78. game:BindToClose(function()
  79.     for i,player in pairs(Players:GetPlayers()) do 
  80.        
  81.         local errormsg = SavePlayerData(player)
  82.         if errormsg then
  83.             warn(errormsg)
  84.         end        
  85.     end
  86.     wait(2)
  87. end)
Add Comment
Please, Sign In to add comment