Advertisement
MrUnintelligent

Roblox Datastore

Sep 11th, 2019
5,097
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 1 0
  1. --LeaderBoard Script:
  2.  
  3. game.Players.PlayerAdded:connect(function(p)
  4. local stats = Instance.new("IntValue")
  5. stats.Name = "leaderstats"
  6. stats.Parent = p
  7.  
  8. local money = Instance.new("IntValue")
  9. money.Name = "Money"
  10. money.Value = 10
  11. money.Parent = stats
  12. end)
  13.  
  14.  
  15. --Datastore Script:
  16.  
  17. local AUTO_SAVE = false -- Make true to enable auto saving
  18. local TIME_BETWEEN_SAVES = 60 -- In seconds (WARNING): Do not put this lower than 60 seconds
  19. local PRINT_OUTPUT = false -- Will print saves and loads in the output
  20. local SAFE_SAVE = false -- Upon server shutdown, holds server open to save all data
  21. ---------------------------------
  22.  
  23. local players = game:GetService("Players")
  24. local dataStoreService = game:GetService("DataStoreService")
  25. local leaderboardData = dataStoreService:GetDataStore("LeaderStats")
  26.  
  27. local function Print(message)
  28. if PRINT_OUTPUT then print(message) end
  29. end
  30.  
  31. local function SaveData(player)
  32. if player.userId < 0 then return end
  33. player:WaitForChild("leaderstats")
  34. wait()
  35. local leaderstats = {}
  36. for i, stat in pairs(player.leaderstats:GetChildren()) do
  37. table.insert(leaderstats, {stat.Name, stat.Value})
  38. end
  39. leaderboardData:SetAsync(player.userId, leaderstats)
  40. Print("Saved "..player.Name.."'s data")
  41. end
  42.  
  43. local function LoadData(player)
  44. if player.userId < 0 then return end
  45. player:WaitForChild("leaderstats")
  46. wait()
  47. local leaderboardStats = leaderboardData:GetAsync(player.userId)
  48. for i, stat in pairs(leaderboardStats) do
  49. local currentStat = player.leaderstats:FindFirstChild(stat[1])
  50. if not currentStat then return end
  51. currentStat.Value = stat[2]
  52. end
  53. Print("Loaded "..player.Name.."'s data")
  54. end
  55.  
  56. players.PlayerAdded:connect(LoadData)
  57. players.PlayerRemoving:connect(SaveData)
  58.  
  59. if SAFE_SAVE then
  60. game.OnClose = function()
  61. for i, player in pairs(players:GetChildren()) do
  62. SaveData(player)
  63. end
  64. wait(1)
  65. end
  66. end
  67.  
  68. while AUTO_SAVE do
  69. wait(TIME_BETWEEN_SAVES)
  70. for i, player in pairs(players:GetChildren()) do
  71. SaveData(player)
  72. end
  73. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement