How can I check if the player presses 1 of 5 buttons in a frame?

I am making a system where a new frame pops up depending on which button the player clicks. I have 5 buttons in a frame, and I want to show a different frame when they click a different button. I thought of putting 5 functions in a scripts and checking it for each of them, but I feel like there is a better way. Can I use tables to do this? How would I go about this?

Tables are a great way to do this to generalize what button a frame will open. Although there are many ways of doing this, using a dictionary might be the best as you can store 2 values easily in one table. It’s also great because you can find the frame to open using the index if you know the button, although here I just loop through the table.

local buttonToFrameToOpen = {
	-- This is a template with the frameToOpen being the value and the button being the index
	[button] = frameToOpen
}
for button, frameToOpen in pairs(buttonToFrameToOpen) do
	button.MouseButton1Click:Connect(function())
		-- Insert code to open the frameToOpen variable here
	end
end
1 Like

an easier to understand script would be this:

in a local script thats parented to the frame, do;

for _, v in pairs(script.Parent:GetChildren()) do
	if v:IsA("TextButton") or v:IsA("ImageButton") then
		v.MouseButton1Click:Connect(function()
			print(v.Name, "Clicked")
		end)
	end
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.