Inventory datastore not working despite no errors?
I was writing an inventory datastore script that saves the items in the player's inventory and loads in when they join in the game next time. However, when I leave the game and join back, the weapons in my inventory I had previously don't load in my inventory now. No errors appeared on the output and there were no error messages in the pcall functions.
I put some weapons in a folder named Weapons which were in ServerStorage so I can see if the player has any weapons.
Script (A regular script in ServerScriptService):
01 | > local DSS = game:GetService( "DataStoreService" ) |
02 | > local InventoryDS = DSS:GetDataStore( "InventoryDS" ) |
03 | > local Players = game:GetService( "Players" ) |
05 | > local function onPlayerAdded(plr) |
06 | > local key = "User_" ..plr.UserId |
07 | > local inventoryReference = game.ServerStorage.Weapons |
10 | > local success, errorMessage = pcall ( function () |
11 | > inventoryData = InventoryDS:GetAsync(key) |
13 | > if inventoryData then |
15 | > for i, weaponName in pairs (inventoryData) do |
16 | > local weapon = inventoryReference:FindFirstChild(weaponName, true ) |
19 | > local weaponClone = weapon:Clone() |
20 | > weaponClone.Parent = plr.Inventory |
27 | > print (plr.Name.. "'s inventory loaded successfully!" ) |
29 | > print ( "There was an error. " ..errorMessage) |
33 | > local function onPlayerRemoving(plr) |
34 | > local key = "User_" ..plr.UserId |
35 | > local playerInventory = plr.Backpack:GetChildren() |
37 | > local playerInventoryTable = { } |
39 | > local success, errorMessage = pcall ( function () |
40 | > InventoryDS:SetAsync(key,playerInventoryTable) |
42 | > for i,weapon in pairs (playerInventory) do |
44 | > table.insert(playerInventoryTable, weapon.Name) |
49 | > print (plr.Name.. "'s inventory saved successfully!" ) |
51 | > print ( "There was an error. " ..errorMessage) |
56 | > Players.PlayerAdded:Connect(onPlayerAdded) |
57 | > Players.PlayerRemoving:Connect(onPlayerRemoving) |
As always, thank you for taking the time to read the script and I will appreciate any help I receive.