I have a script in one of my games that handles money being given out every 5 minutes, and I need it to save to the datastore so when the player rejoins the game after buying/earning the money they keep it, instead of their money counter resetting.
The code is here to help you understand what I am talking about:
game.Players.PlayerAdded:Connect(function(Plr) local Stats = Instance.new("Folder", Plr) Stats.Name = "leaderstats" local Cash = Instance.new("IntValue", Stats) Cash.Name = "Cash" Cash.Value = 0 local DS = game:GetService("DataStoreService") game.Players.PlayerRemoving:Connect(function() DS:SetAsync(Plr.userId.."_DS", Cash.Value) end) while true do wait(300) for i, v in pairs(game.Players:GetPlayers()) do v.leaderstats.Cash.Value = v.leaderstats.Cash.Value + 100 end end end)
As you can see in the script above I tried getting an understanding of the Datastore service
local DS = game:GetService("DataStoreService") game.Players.PlayerRemoving:Connect(function() DS:SetAsync(Plr.userId.."_DS", Cash.Value) end)
But, that did not work. Could I get some help on this?
YOU NEED TO COPY THIS ALL DOWN. SOME OF IT WONT COME UP AS A SCRIPT BUT COPY AND PASTE THIS ALL INTO A NEW SCRIPT IN SERVER SCRIPT SERVICE
local DS = game:GetService("DataStoreService"):GetDataStore("SaveData") game.Players.PlayerAdded:Connect(function(plr) wait() local plrkey ="id_"..plr.userId local save1 = plr.leaderstats.Kills
local GetSaved = DS:GetAsync(plrkey) if GetSaved then save1.Value = GetSaved[1] else local NumberForSaving = {save1.Value} DS:GetAsync(plrkey, NumberForSaving) end
end)
game.Players.PlayerRemoving:Connect(function(plr) DS:SetAsync("id_"..plr.userId, {plr.leaderstats.Cash.Value}) end)