Message
Message
-- Services
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local DataStoreService = game:GetService("DataStoreService")
local HttpService = game:GetService("HttpService")
-- Remote Event
local RemoteEvent = Instance.new("RemoteEvent")
RemoteEvent.Name = "InventoryRemoteEvent"
RemoteEvent.Parent = ReplicatedStorage
-- DataStore
local InventoryDataStore = DataStoreService:GetDataStore("InventoryDataStore")
-- Item Class
local Item = {}
Item.__index = Item
function Item:ToTable()
return {
Name = self.Name,
Description = self.Description,
Category = self.Category
}
end
-- Inventory Class
local Inventory = {}
Inventory.__index = Inventory
function Inventory.new()
local self = setmetatable({}, Inventory)
self.Items = {}
return self
end
function Inventory:AddItem(item)
table.insert(self.Items, item)
end
function Inventory:RemoveItem(name)
for i, item in ipairs(self.Items) do
if item.Name == name then
table.remove(self.Items, i)
break
end
end
end
function Inventory:GetItems()
local itemsTable = {}
for _, item in ipairs(self.Items) do
table.insert(itemsTable, item:ToTable())
end
return itemsTable
end
function Inventory:SaveToDataStore(playerId)
local success, err = pcall(function()
local itemsTable = self:GetItems()
local jsonData = HttpService:JSONEncode(itemsTable)
InventoryDataStore:SetAsync(tostring(playerId), jsonData)
end)
if not success then
warn("Failed to save inventory for player " .. tostring(playerId) .. ":
" .. err)
end
end
function Inventory:LoadFromDataStore(playerId)
local success, jsonData = pcall(function()
return InventoryDataStore:GetAsync(tostring(playerId))
end)
if success and jsonData then
local itemsTable = HttpService:JSONDecode(jsonData)
self.Items = {}
for _, itemData in ipairs(itemsTable) do
local item = Item.new(itemData.Name, itemData.Description,
itemData.Category)
self:AddItem(item)
end
else
warn("Failed to load inventory for player " .. tostring(playerId) .. ":
" .. (jsonData or "No data"))
end
end