I have recently been making a game, where I need to save several numbers, like for instance: money, items and more. I have this script. It saves money data. How would I make it save more than one item.
local DataStoreService = game:GetService("DataStoreService") local MyData = DataStoreService:GetDataStore("MyData") --Getting Data and Creating leaderboard game.Players.PlayerAdded:Connect(function(player) local leaderstats = Instance.new("Folder") leaderstats.Name = "leaderstats" leaderstats.Parent = player local Money = Instance.new("IntValue") Money.Name = "Money" Money.Parent = leaderstats local Data local Sucess, ErroMessage = pcall(function() Data = MyData:GetAsync(player.UserId.."-Money") end) if Sucess == true then Money.Value = Data else print("There was an error") warn(ErroMessage) end end) --Saving Data game.Players.PlayerRemoving:Connect(function(player) local Sucess, ErrorMessage = pcall(function() MyData:SetAsync(player.UserId.."-Money", player.leaderstats.Money.Value) end) if Sucess == true then print("PlayerData sucessfully saved") else print("There was an error") warn(ErrorMessage) end end)
If you want to save multiple values in a single Datastore, tables are your best friend!
tableToSave = {Money = 100, Level = 1} local Sucess, ErrorMessage = pcall(function() MyData:SetAsync(player.UserId, tableToSave) end)
Loading and reading that data:
local Data local Sucess, ErroMessage = pcall(function() Data = MyData:GetAsync(player.UserId) end) if Sucess == true then Money.Value = Data.Money Level.Value = Data.Level else print("There was an error") warn(ErroMessage) end
I used the code you provided with the addition to the 'Level' value as an example. Hope I could help you!