Issue with displaying numbers

I’m making an inventory UI which displays the items you have in your backpack, along with the amount of them. (you have 3 guns, it displays a gun with a 3 next to it.)

Something weird is going on:

local plr = game.Players.LocalPlayer
local char =  plr.Character or plr.CharacterAdded:Wait()
local hum = char:WaitForChild("Humanoid")
-----------------------------------------------------------------------------
local scrollingframe = script.Parent
local gui = script.Parent.Parent

local inv = game:GetService("ReplicatedStorage").InventoryStuff.Tools
local itemUI = game:GetService("ReplicatedStorage").InventoryStuff.ItemUI

local contents = {}
--------------------------------------------------------------------------------
local function GetChildrenWithSameNames(Directory, TargetName)
	local Children = {}

	for _, Obj in pairs(Directory:GetChildren()) do
		if Obj.Name == TargetName then
			table.insert(Children, Obj)
		end
	end

	return Children
end
--------------------------------------------------------------------------------
for i,v in pairs(plr.Backpack:GetChildren()) do
	task.spawn(function()
		local name = v.Name
		if not table.find(contents, name) then
			local newItemUI = itemUI:Clone()
			table.insert(contents, name)
			local children = GetChildrenWithSameNames(plr.Backpack,v.Name)
			local amount = #children
			local amountui = itemUI.Amount
			print(name, amount)
			newItemUI.Parent = scrollingframe
			newItemUI.Name = name
			newItemUI.Image.Image = inv[name].Image.Value
			amountui.Visible = true
			amountui.Text = tostring(amount)
		end
	end)
end

It prints the correct number of the items in my inventory (3 crowbars, 1 pistol, 2 flashlights)

The number (amountui.Text) displays 0 crowbars, 3 guns, 1 flashlight.
I use the same variable

What could be causing this?

This has some unusual stuff going on. Why do you use task.spawn?

Try this.

amountui.Text = amount

Or

amountui.Text = #children

Hope this helped!

local amountui = itemUI.Amount
looks like it should be …
local amountui = newItemUI.Amount

1 Like

You should include a demo download or steps to remake this.