Connect function to each new added child?

Is it possible to connect a function to an ImageButton which was cloned without using a separate script? I’ve tried this, but it didn’t work.

Grid.ChildAdded:connect(function(instance)
    instance.MouseButton1Click:connect(function() 
		print("123")
	end)
end)
Summary

This solution uses coroutines to create a listener every time a button is cloned.

local Frame = script.Parent

Frame.ChildAdded:Connect(function(instance)
	if instance:IsA('TextButton') then -- If the child is a button...
		print("The new child is a button")
		local setListener = coroutine.create(function(instance) -- Create a new function via coroutine
			instance.MouseButton1Click:Connect(function() -- A new listener is created
				print("123")
			end)
		end)
		coroutine.resume(setListener, instance) -- Run the new coroutine
	else
		print("The new child is not a button.") -- oof
	end
end)

-- The function above will run for each button that is cloned into the frame.

local b = script.Parent.TextButton:Clone()
b.Parent, b.Name, b.Text = Frame, 'NewButton', 'NewButton'

b = script.Parent.TextButton:Clone()
b.Parent, b.Name, b.Text = Frame, 'NewButton2', 'NewButton2'

b = script.Parent.TextButton:Clone()
b.Parent, b.Name, b.Text = Frame, 'NewButton3', 'NewButton3'

Feel free to test this in Studio. I used the following structure:
15

Edit: This solution is not efficient. Your code is correct.

1 Like

vsnry, your solution looks right (though you can add extra safety by checking if instance:IsA(“ImageButton”) like Ysko did).
Maybe try adding print statements before you create the new connections to see what’s going wrong?

like this
print("this code is running"); --Sometimes your code just doesn't run. ¯\_(ツ)_/¯
Grid.ChildAdded:connect(function(instance)
    print("new child: ", instance, instance and instance.ClassName);
    instance.MouseButton1Click:connect(function() 
		print("123")
	end)
end)

@Ysko, coroutines might be unnecessary for this job. They’re good if you need to start and stop execution flow, but here you’re just creating a connection in one shot and the coroutine dies.

Are you sure there’s nothing before that code that’s stopping the script from running that event?

I tried this and it worked fine

workspace.ChildAdded:Connect(function(c)
	c.Changed:Connect(function(p)
		print(p)
	end)
end)

You’re absolutely right. I didn’t check if the original code works :sweat_smile: my bad.
I’d avoid coroutines as much as possible.

Ahhh, I found out why it didn’t work.

It had something to do with modules running before localscripts or something because I was creating the buttons inside the module like this

image

Doing it like this fixed it as the function ran after the script started looking for new children to be added

image