Inventory System (With datastore)

local httpService = game:GetService(“HttpService”)

game.Players.PlayerRemoving:Connect(function(player)
local dataToSave = {}
local gold = player.Gold – the value of the players gold

local inventory = {}
for _, v in pairs(player.Inventory) do -- loop through the players inventory
	local item = {}
	table.insert(item, v.Id) -- the id value
	table.insert(item, v.Name) -- the item name
	table.insert(item, v.Description) -- the item description
	table.insert(inventory, item) -- insert item into invertory
end
table.insert(dataToSave, gold)
table.insert(dataToSave, inventory)

dataToSave = httpService:JSONEncode(dataToSave)
-- save the dataToSave string

end)

game.Players.PlayerAdded:Connect(function(player)
local data = ds:GetAsyc(player.UserId)
– obviously test to see if the data is actually there before you do this
data = httpService:JSONDecode(data)
player.Gold = data[1]

for _, v in pairs(data[2]) do
	local itemId = v[1]
	local itemName = v[2]
	local itemDescription = v[3]
	--- do what ever you want with loaded stuff down here. AKA make the item and put it in player inventory
end
end)

– note that since you are assigning unique ids to every item, its pointless to save the name and description. save the id
– and when loading each item, give it its name and description based on the id.
– sorry if this is confusing, i am known to be very bad at explaining things :slight_smile:

2 Likes