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:
Edit: This solution is not efficient. Your code is correct.
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.