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)