Inventory Saver not working

Hello, I have this Inventory Saver here. It doesn’t work and I want it, when someone dies and the item is on his hands, the tools will get saved. Also, when the player dies, I want the tools to disappear and when the player respawns he will not have tools.

local InventoryDataStore = DataStoreService:GetDataStore("PlayerInventoryData")

-- Function to save player's inventory
local function saveInventory(player)
	local playerId = player.UserId
	local playerInventory = player:WaitForChild("Backpack"):GetChildren()

	local success, error = pcall(function()
		InventoryDataStore:SetAsync(tostring(playerId), playerInventory)
	end)

	if not success then
		warn("Failed to save inventory for player " .. playerId .. ": " .. error)
	end
end

-- Function to load player's inventory
local function loadInventory(player)
	local playerId = player.UserId

	local success, savedInventory = pcall(function()
		return InventoryDataStore:GetAsync(tostring(playerId))
	end)

	if success and savedInventory then
		local backpack = player:WaitForChild("Backpack")

		for _, item in ipairs(savedInventory) do
			item.Parent = backpack
		end
	end
end

-- Event: Player added
game.Players.PlayerAdded:Connect(function(player)
	loadInventory(player)

	-- Event: Player leaving
	player.CharacterRemoving:Connect(function()
		saveInventory(player)
	end)
end)

Are you testing in studio or on roblox? if in studio try it on roblox.

Are there any errors?

There are no erros. Okay i will test it there.

I joined the game it didn’t save the tools

did you join get them, leave then rejoin or just joined and didn’t have them?

I joined the game, I got the tool then I left and rejoined. It didn’t save.

I think your problem is the for loop as your looping through saveedInventory and trying to parent that to the players backpack even though savedInventory is not the actual game object but rather a table.

So, what should I change to the script?