Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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):

> local DSS = game:GetService("DataStoreService")
> local InventoryDS = DSS:GetDataStore("InventoryDS")
> local Players = game:GetService("Players")
> 
> local function onPlayerAdded(plr)
> 	local key = "User_"..plr.UserId
> 	local inventoryReference = game.ServerStorage.Weapons
> 	
> 	local inventoryData
> 	local success, errorMessage = pcall(function()
> 		inventoryData = InventoryDS:GetAsync(key)
> 		
> 		if inventoryData then
> 			print("check")
> 			for i, weaponName in pairs(inventoryData) do
> 				local weapon = inventoryReference:FindFirstChild(weaponName,true)
> 				if weapon then
> 					print("1")
> 					local weaponClone = weapon:Clone()
> 					weaponClone.Parent = plr.Inventory
> 				end
> 			end
> 		end
> 	end)
> 	
> 	if success then
> 		print(plr.Name.."'s inventory loaded successfully!")
> 	else
> 		print("There was an error. "..errorMessage)
> 	end
> end
> 
> local function onPlayerRemoving(plr)
> 	local key = "User_"..plr.UserId
> 	local playerInventory = plr.Backpack:GetChildren()
> 	
> 	local playerInventoryTable = {}
> 	
> 	local success, errorMessage = pcall(function()
> 		InventoryDS:SetAsync(key,playerInventoryTable)
> 		
> 		for i,weapon in pairs(playerInventory) do
> 			print("2")
> 			table.insert(playerInventoryTable, weapon.Name)
> 		end
> 	end)
> 	
> 	if success then
> 		print(plr.Name.."'s inventory saved successfully!")
> 	else
> 		print("There was an error. "..errorMessage)
> 	end
> 	
> end
> 
> Players.PlayerAdded:Connect(onPlayerAdded)
> Players.PlayerRemoving:Connect(onPlayerRemoving)

As always, thank you for taking the time to read the script and I will appreciate any help I receive.

1 comment

0

Is enable api services turned on

1 answer

✓ Accepted answer

Looks like you're saving your inventory before actually adding any weapons to the table that's being saved.

Consider changing the order of:

InventoryDS:SetAsync(key,playerInventoryTable)
   
for i,weapon in pairs(playerInventory) do
	print("2")
	table.insert(playerInventoryTable, weapon.Name)
end

to:

for i,weapon in pairs(playerInventory) do
	print("2")
	table.insert(playerInventoryTable, weapon.Name)
end

InventoryDS:SetAsync(key,playerInventoryTable)

This discussion is preserved as it was. New answers, comments, and votes are closed.