Hi all,
Am I autosaving this data correctly? Currently, I am giving players money every 5 minutes, and autosaving it. Is this correct? Please feel free to tear my code to pieces, the feedback is really appreciated! Thank you!
local DataStoreService = game:GetService("DataStoreService")
local myDataStore = DataStoreService:GetDataStore("Money")
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "Stats"
leaderstats.Parent = player
local cash = Instance.new("IntValue")
cash.Name = "Money"
cash.Parent = leaderstats
local data
local success, errormessage = pcall(function()
data = myDataStore:GetAsync(player.UserId.."-cash")
end)
if success then
cash.Value = data
else
print("There was an error while getting your data")
warn(errormessage)
end
local AUTOSAVE_INTERVAL = 300 -- 5 Minutes
-- Function to periodically save player data
local function autoSave()
while wait(AUTOSAVE_INTERVAL) do -- two parts to this, first is giving players more money, then saving it
--Part 1, give everyone +20 money
local amount = 20 -- amount of cash given after every time delay
local currencyname = "Money"
if player:FindFirstChild("Stats") then
player.Stats[currencyname].Value = player.Stats[currencyname].Value + amount
end
--now save it
local success, errormessage = pcall(function()
myDataStore:SetAsync(player.UserId.."-cash",player.Stats.Money.Value)
end)
if success then
print("Player Data successfully saved")
else
print("There was an error when saving data")
warn(errormessage)
end
end
end
-- Start running "autoSave()" function in the background
spawn(autoSave)
end)
Does this look correct, or is there a better way of doing this? Thank you!