I have attempted to make a system to save the inventory of someone(the tools in their backpack) and load them in when they re-join, but it isn't working or returning any errors. Nothing is being printed to the inventory.
--Sorry my code is a bit messy local serverStorage = game:GetService("ServerStorage") local dss = game:GetService("DataStoreService") local inventoryStore = dss:GetDataStore("Inventory") game.Players.PlayerAdded:connect(function(plr) local key = "user_"..plr.userId print(inventoryStore:GetAsync(key)) if inventoryStore:GetAsync(key) then do repeat wait() until plr:FindFirstChild("Backpack") for i,v in ipairs(inventoryStore:GetAsync(key)) do if v.Name == "MP5" then do serverStorage:WaitForChild("MP5"):clone().Parent = plr.Backpack print("loading mp5") end else if v.Name == "Police Baton" then do serverStorage:WaitForChild("Police Baton"):clone().Parent = plr.Backpack print("loading baton") end end end end end end end) game.Players.PlayerRemoving:connect(function(plr) local key = "user_"..plr.userId local saveInventory = {} for _,item in pairs(plr.Backpack:GetChildren()) do table.insert(saveInventory,1,item.Name) end inventoryStore:SetAsync(key, saveInventory) for _,item in (saveInventory) do print(item.Name) end end)
It seemed like you took a few unnecessary steps, but otherwise, you had the right idea. One of the biggest issues I saw was table.insert(saveInventory, 1, item.Name)
, which should have inserted the item's Name at index 1 of the table every time. This would overwrite the previous value. Other than that, you don't look very comfortable with if then / else / elseif / end
. You have a particular line in which you spam end
, presumably because you didn't know how many you needed.
As you said, your code is messy, so do try to clean it up a little bit. It will help you in the long run if you establish a method to writing code.
Anyway, try something like this:
local storage = game.ServerStorage; local inventorystore = game:GetService("DataStoreService"):GetDataStore("Inventory"); game.Players.PlayerAdded:connect(function(player) local store = inventorystore:GetAsync("user_" .. player.userId); if(store)then local backpack = player:WaitForChild("Backpack", 10); for a, x in pairs(store) do storage:WaitForChild(x.Name):Clone().Parent = backpack; end end end) game.Players.PlayerRemoving:connect(function(player) local inventory = {}; for a, x in pairs(player.Backpack:GetChildren()) do table.insert(inventory, x.Name); print(inventory[a], x); end inventorystore:SetAsync("user_" .. player.userId, inventory); end)