Detecting if any of the GUI buttons were clicked?

  1. What do I want to achieve? Detect if any of the GUI buttons were clicked.

  2. What is the issue? I can’t find a solution to it, nothing I tried worked.

  3. What solutions have I tried so far? I tried inserting this script in a Frame In a GUI, did not work.

local ScreenGui = script.Parent

ScreenGui.DescendantAdded:Connect(function(Descendant)
	if Descendant:IsA("TextButton") or Descendant:IsA("ImageButton") then
		Descendant.MouseButton1Down:Connect(function()
			print("Button name is "..Descendant.Name)
		end)
	end
end)
1 Like

DescendantAdded may have fired before this part of this script has ran. Loop through the descendants of the ScreenGui to connect to the buttons added before this part of the script has ran.

What would that look like in code?

local ScreenGui = script.Parent

local function ConnectDescendant(Descendant)
	if Descendant:IsA("TextButton") or Descendant:IsA("ImageButton") then
		Descendant.MouseButton1Down:Connect(function()
			print("Button name is "..Descendant.Name)
		end)
	end
end

ScreenGui.DescendantAdded:Connect(ConnectDescendant)

for _, Descendant in ScreenGui:GetDescendants() do
	ConnectDescendant(Descendant)
end

Thank you, it works!

character minimum moment

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