Adding InputBegan event to multiple instances

Hello all, the situation is fairly easy yet it doesn’t seem to work.
I loop thru a dictionary and each time I clone a frame and add this cloned frame to UIGridLayout which is inside a scrolling frame (see this
Changing frame position in UIGridLayout)

for _, item in ipairs(items) do
	itemFrame = itemTemplate:Clone()
	itemFrame.Parent = script.Parent.InventoryFrame[path]
	itemFrame.ItemName.Text =
	itemFrame.ItemRarity.Text = item.rarity
	itemFrame.ItemRarityColor.BackgroundColor3 = item.rarityColor
	        if input.UserInputType == Enum.UserInputType.MouseButton1 then
		        draggable = true
		        while wait() do
			        if draggable then
				        itemFrame.Parent = script.Parent.InventoryFrame
				        itemFrame.Position =, mouse.X, 0, mouse.Y)
		if input.UserInputType == Enum.UserInputType.MouseButton1 then
			draggable = false

But for some reason, it seems like the InputBegan works only for the last element of the loop. Is this a good approach? Can InputBegan be used multiple times? If not what should I use to check if each cloned frame is clicked and change its position to mouse position till player lets mouse button?

1 Like

You need to make itemFrame a variable that is local to the scope of the loop, otherwise it gets overwritten on the next iteration, and since the event handler functions reference that variable, they’re referencing the last-set value (which ends up being the last frame), not the value at the time of initialization.

Simply changing the clone line to…

local itemFrame = itemTemplate:Clone()

…should fix the problem.