Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Script help? (Summarizing an event)

There's gotta be a better way to shorten this. I'm trying to make a function where it detects when one of its child's ImageButtons have been clicked, and then identifies the button that was clicked. It is way easier than to make a new function for every single button. How should I do this? Is there a certain function or event to do so?

Thanks, hopefully I explained this correctly.

1 answer

✓ Accepted answer

yes, there is.

you'll want to use a for loop and :GetChildren() to identify all the image buttons.

local frameWithImageButtons = script.Parent --where are all the image buttons located?
local imageButtons = frameWithImageButtons:GetChildren()
for i=1, #imageButtons do --loop through all the buttons
	 --Connect to the buttons click event
	local imageButton = imageButtons[i] --get the image button in the array
	imageButton.MouseButton1Click:Connect(function()
		--[[imageButton is a local variable unique in the scope of one iteration of the for loop,
		so it will connect to each individual button.]]
		print(imageButton.Name..' was clicked.')
	end)
end

4 comments

1

Why not use a Generic-For instead of Numeric in this case?

0

numeric is slightly faster

0

Wow. The difference is so small it's not even worth it. Use generic loops.

0

it literally doesn't matter

This discussion is preserved as it was. New answers, comments, and votes are closed.