Problem with saving player's inventory

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.

2 Likes

PlayerRemoving doesn’t fire in Studio, try testing it out in a live game. Also this is an example of how not to use pcalls.

When using pcalls, make sure you catch an error.

local success, err = pcall(function()
-- your code
end)

if err then
warn(string.format("!! ERROR: %s !!", err);
elseif success then
print('Saved success!)
end
1 Like

For reference, I would suggest replacing your pcall with something like this:

local ok, res = pcall(dS.GetAsync, dS, key)

if not ok then error(res) end

if not res then res = {--[[starterItems]]} end

for i, v in pairs(res) do
	local item = game.ServerStorage:FindFirstChild(v)
	
	if not item then continue end
	
	item:Clone().Parent = player:WaitForChild("Inventory")
end

Also, you need to enable studio access to use data stores.

Make that player.UserId since it’s all caps-sensitive.