Problem with stacking in inventory system

I have this inventory handler script that gathers the items from the backpack and updates them in the inventory GUI.

But the problem is that even when I reach 0 of a certain item it stills shows up a ghost icon of it on the inventory. I don’t know how to destroy the cloned sample of an item i don’t have in my backpack anymore

local players = game:GetService("Players")
local plr = players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()

local sample = script.Sample

local bp = plr.Backpack

local itens = bp:GetChildren()

local inv = {}

while wait(0.1) do
	
	for i, item in pairs(bp:GetChildren()) do

		if not script.Parent.Itens:FindFirstChild(item.Name) then

			local clone = sample:Clone()
			clone.Name = item.Name
			clone.nome.Text = item.Name
			clone.Image = item.TextureId

			clone.Parent = script.Parent.Itens

		else

			local dupes = 0

			for i, duplicated in pairs(bp:GetChildren()) do

				if duplicated.Name == item.Name then

					dupes += 1
			
				end

			end

			script.Parent.Itens:FindFirstChild(item.Name).quantity.Text = tostring(dupes).."x"

		end
		
	end
	
end

use table.remove or something like that

local players = game:GetService("Players")
local plr = players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()

local sample = script.Sample
local bp = plr.Backpack
local inv = {}

while wait(0.1) do
    for i, item in pairs(bp:GetChildren()) do
        local existingItem = script.Parent.Itens:FindFirstChild(item.Name)
        if not existingItem then
            local clone = sample:Clone()
            clone.Name = item.Name
            clone.nome.Text = item.Name
            clone.Image = item.TextureId
            clone.Parent = script.Parent.Itens
        else
            local dupes = 0
            for i, duplicated in pairs(bp:GetChildren()) do
                if duplicated.Name == item.Name then
                    dupes += 1
                end
            end
            existingItem.quantity.Text = tostring(dupes).."x"
        end
    end
    
    -- Remove UI elements for items no longer in the backpack
    for _, itemUI in ipairs(script.Parent.Itens:GetChildren()) do
        if not bp:FindFirstChild(itemUI.Name) then
            itemUI:Destroy()
        end
    end
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.