Hi! I’ve been working on a system that saves the player’s inventory, it works just fine. However, there is a quite annoying bug. It’s that if I have multiple of the same items in my inventory, and if I’m NOT holding one of those items (that there are multiple of in my inventory) and I leave the game, then I get an extra of the same item next time I join the game!
So I’ve been trying to look on other posts for people that have the same problem as me, but I haven’t found any posts yet that relates to this. And I’ve asked ChatGPT and stuff. So please help me fix this. Can you also give me some code for the solution or something, because I’m pretty new to Lua.
local ItemsFolder = game:GetService("ServerStorage"):WaitForChild('Items')
local players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local MainStore = DataStoreService:GetDataStore('Inventory')
local function PlayerAdded(plr)
repeat
task.wait()
until plr.Character
task.wait(1)
local success, inventory = pcall(function()
return MainStore:GetAsync(plr.UserId)
end)
if not success then
print("Error loading inventory for", plr.Name, inventory)
inventory = {} -- Fallback to an empty inventory
end
for itemName, quantity in pairs(inventory) do
local item = ItemsFolder:FindFirstChild(itemName)
if item then
for i = 1, quantity do
local clone = item:Clone()
clone.Parent = plr.Backpack
clone:Clone().Parent = plr.StarterGear
end
else
print('You need to put', itemName, 'in the items folder in server storage')
end
end
end
local function PlayerLeft(plr)
local backpack = plr.Backpack
local char = plr.Character
local ItemsTable = {}
task.wait(0.5)
local currentlyHeldItem = nil
if char then
local tool = char:FindFirstChildOfClass('Tool')
if tool then
currentlyHeldItem = tool.Name
end
end
if not currentlyHeldItem then
local toolInGear = plr.StarterGear:FindFirstChildOfClass('Tool')
if toolInGear then
currentlyHeldItem = toolInGear.Name
end
end
for _, object in pairs(backpack:GetChildren()) do
if object:IsA('Tool') then
local toolName = object.Name
if ItemsTable[toolName] then
ItemsTable[toolName] = ItemsTable[toolName] + 1
else
ItemsTable[toolName] = 1
end
end
end
if currentlyHeldItem then
if ItemsTable[currentlyHeldItem] then
ItemsTable[currentlyHeldItem] = ItemsTable[currentlyHeldItem] + 1
else
ItemsTable[currentlyHeldItem] = 1
end
end
local success, err = pcall(function()
return MainStore:SetAsync(plr.UserId, ItemsTable)
end)
if not success then
plr:Kick("There was an error when saving your inventory, please join the game again.")
print("Error saving inventory for", plr.Name, err)
end
end
players.PlayerAdded:Connect(PlayerAdded)
players.PlayerRemoving:Connect(PlayerLeft)