Keep for i, v in pairs loop updated

Hello, I’m currently working on a system in which I need to add and remove Text Buttons but also continuously detect them being clicked. I’ve noticed that whenever I add a new button it is no longer detected being clicked.

This is the original code:

for i, v in pairs(script.Parent:WaitForChild("Settings"):GetChildren()) do
	if v:IsA("TextLabel") then
		for i, button in pairs(v:GetChildren()) do
			if button:IsA("TextButton") then
				button.Activated:Connect(function()
					if button.Name == "Delete" then
						print(button.Name)
					elseif button.Name == "Down" then
						print(button.Name)
					else
						print(button.Name)
					end
				end)
			end
		end
	end
end

I came to the conclusion that the for loop wasn’t being updated constantly so I tried to come up with a workaround using coroutines, but whenever a button is clicked, it prints the buttons name up to 50 times.

local checkClicks = coroutine.wrap(function()
	while true do
		for i, v in pairs(script.Parent:WaitForChild("Settings"):GetChildren()) do
			if v:IsA("TextLabel") then
				for i, button in pairs(v:GetChildren()) do
					if button:IsA("TextButton") then
						button.Activated:Connect(function()
							if button.Name == "Delete" then
								print(button.Name)
							elseif button.Name == "Down" then
								print(button.Name)
							else
								print(button.Name)
							end
						end)
					end
				end
			end
		end
		wait()
	end
end)()

The goal is for the for loop to keep the buttons constantly updated so it can detect new buttons being clicked, any help would be much appreciated!

for i, v in pairs(script.Parent:WaitForChild("Settings"):GetChildren()) do
	if v:IsA("TextLabel") then
		function func(button)
			if button.Name == "Delete" then
				print(button.Name)
			elseif button.Name == "Down" then
				print(button.Name)
			else
				print(button.Name)
			end
		end
		
		for i, button in pairs(v:GetChildren()) do
			if button:IsA("TextButton") then
				button.Activated:Connect(function()
					func(button)
				end)
			end
		end
		
		v.ChildAdded:Connect(function(child)
			if child:IsA("Button") then
				child.Activated:Connect(function()
					func(child)
				end
			end
		end)
	end
end

Just use a childAdded function.

1 Like

That did the trick, thank you.