LawMixer

DatastoreSaving

Jul 30th, 2021
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. local DEFAULT_VALUE = 5 -- Starting value of credits
  2. local UNSUCCESSFUL_RETRY_TIME = 5 -- Retry time in case of unsuccessful credit save
  3. local CreditCooldown = 5
  4. local IncomeIncrease = 5
  5. local Credit = { }
  6. local QueuedPlayers = { }
  7. local CreditText = game.StarterGui.Credits.Credits.TextLabel
  8. local DataStoreService = game:GetService("DataStoreService")
  9. local CreditData = DataStoreService:GetDataStore("StitchDreamzIsCool")
  10. local RS = game:GetService("RunService")
  11.  
  12.  
  13.  
  14. Credit.SetupPlayer = function(Player)
  15. local Data = Instance.new("Folder")
  16. Data.Name = "Data"
  17. Data.Parent = Player
  18.  
  19. local Successful, Save = Credit:LocateSave(Player)
  20.  
  21. local Credits = Instance.new("IntValue")
  22. Credits.Name = "CREDITS"
  23. Credits.Parent = Data
  24.  
  25. Credits.Value = Save or DEFAULT_VALUE
  26. CreditText.Text = "Credits: " .. Credits.Value
  27.  
  28. while Player do
  29. wait(CreditCooldown)
  30.  
  31. if Player ~= nil and Player:IsDescendantOf(game.Players) then
  32.  
  33. Credits.Value += IncomeIncrease
  34. CreditText.Text = "Credits: " .. Credits.Value
  35. end
  36. end
  37. end
  38.  
  39. function Credit:LocateSave(Player)
  40.  
  41. local UserId = Player.UserId
  42. assert(type(UserId) == "number", "Credit:LocateSave() failed! (Invalid UserId)")
  43.  
  44. local DataReturn = CreditData:GetAsync(UserId)
  45. return DataReturn ~= nil, DataReturn
  46. end
  47.  
  48. function Credit:SavePlayer(Player)
  49.  
  50. if RS:IsStudio() then
  51. return
  52. end
  53.  
  54. local UserId = Player.UserId
  55. -- assert(type(UserId) == "number", "Credit:LocateSave() failed! (Invalid UserId)")
  56.  
  57. local Data = Player:FindFirstChild("DATA"):FindFirstChild("CREDITS")
  58.  
  59. if not Data then
  60. Data = { }
  61. Data["Value"] = DEFAULT_VALUE
  62. end
  63.  
  64. local Successful = pcall(function()
  65. CreditData:SetAsync(UserId, Data.Value)
  66. end)
  67.  
  68. if not Successful then
  69. warn("[DATASTORE] UNSUCCESSFUL SAVE OF ".. Player.Name.. "! RETRYING")
  70. delay(UNSUCCESSFUL_RETRY_TIME, function()
  71. self:SavePlayer(Player)
  72. end)
  73. else
  74. print("[DATASTORE] SUCCESSFUL SAVE OF ".. Player.Name)
  75. end
  76.  
  77. end
  78.  
  79. Credit.SaveAllPlayers = function()
  80. for _, Player in next, game.Players:GetPlayers() do
  81. Credit:SavePlayer(Player)
  82. end
  83. end
  84.  
  85.  
  86. return Credit
  87.  
Advertisement
Add Comment
Please, Sign In to add comment