Hi! I was making an inventory system for my game but I encountered a problem,
My inventory system works by assigning each item a slot number that corresponds to their slot, and I assign it by using this piece of code right here
for i,v in pairs(currentInventory) do
if type(v) == "table" then
v["Slot"] = i
print(currentInventory,"Before")
else
table.remove(currentInventory,i)
end
end
That’s the only code in my scripts that is assigning the slots however when i tried to test it out
I seem to be getting a different result from what i wanted
all the slot had the exact same slot number and weirdly the slot number correlates to how many items I have
Here’s a video
Now I also noticed that when the for loop runs it seems to be assigning the slot number to all of items in the inventory but with the same slot number. It seems to be a bug
My entire code
---Services
local ServerScripts = game:GetService("ServerScriptService")
---Paths
local modules = ServerScripts:WaitForChild("Modules")
---Modules
local PlayerDataHandler = require(modules:WaitForChild("PlayerDataHandler"))
local PlayerInventoryHandler = {}
local function SortSlot(currentInventory,player)
for i,v in pairs(currentInventory) do
if type(v) == "table" then
v["Slot"] = i
print(currentInventory,"BeforeInv")
else
table.remove(currentInventory,i)
end
end
PlayerDataHandler:Update(player,"Slots",function(CurrentSlots)
CurrentSlots = #currentInventory
return CurrentSlots
end)
print(currentInventory,"Inventory")
return currentInventory
end
function PlayerInventoryHandler:AddItem(player,item)
local maxSlots = PlayerDataHandler:Get(player, "MaxSlots")
local CurrentSlots = PlayerDataHandler:Get(player, "Slots")
if CurrentSlots < maxSlots then
PlayerDataHandler:Update(player, "Inventory", function(currentInventory)
if not item.Stackable then
print("this not")
table.insert(currentInventory, item)
SortSlot(currentInventory,player)
return currentInventory
else
print("this")
for i,v in pairs(currentInventory) do
if v.Name == item.Name then
v.Quantity += item.Quantity
print(currentInventory)
return currentInventory
end
end
table.insert(currentInventory, item)
SortSlot(currentInventory,player)
return currentInventory
end
end)
else
print(CurrentSlots, maxSlots)
end
end
function PlayerInventoryHandler:RemoveItem(player,item)
PlayerDataHandler:Update(player, "Inventory", function(currentInventory)
if not item.Stackable then
table.remove(currentInventory, item["Slot"])
SortSlot(currentInventory,player)
return currentInventory
else
for i,v in pairs(currentInventory) do
if v.Name == item.Name then
v.Quantity -= item.Quantity
print(currentInventory)
if v.Quantity <= 0 then
table.remove(currentInventory, item["Slot"])
SortSlot(currentInventory,player)
end
return currentInventory
end
end
print("Item Stackable does not exist")
end
end)
end
return PlayerInventoryHandler