Hi guys. I am new here and I need your help …
I am trying to save player’s inventory. Here is the code i wrote for i get and save data. If i check explorer while playing i can see items in player’s inventory folder. But if i rejoin to game that items will dissapear which means inventory data is not saving or not loading. So code is not working.
I guess there is problem with saving data. I printed out itemsToSave variable and i saw empty table which means items in player’s inventory is not appending to itemsToSave table.
local dS = game:GetService("DataStoreService"):GetDataStore("Inventory")
game.Players.PlayerAdded:Connect(function(player)
local Inventory = Instance.new('Folder')
Inventory.Name = 'Inventory'
Inventory.Parent = player
local key = "id-"..player.userId
pcall(function()
local items = dS:GetAsync(key)
if items then
for i, v in pairs(items) do
local item = game.ServerStorage.FindFirstChild(v, true)
if item then
item:Clone().Parent = player:WaitForChild('Inventory')
end
end
end
end)
end)
game.Players.PlayerRemoving:Connect(function(player)
local key = 'id-'..player.userId
pcall(function()
local itemsToSave = {}
for i, v in pairs(player.Inventory:GetChildren()) do
if v then
table.insert(itemsToSave, v.Name)
end
end
dS:SetAsync(key, itemsToSave)
print(itemsToSave)
end)
end)
Btw, I just wrote this code after learning from one youtube video
Ask me if you have any questions.