Shortcut for multiple TextButtons

Hello,

I’m trying to make a shortcut in my script to bypass repetitive lines of code.

I have a ScreenGui with multiple TextButtons that will basically all do the same function. I was hoping that I would be able to create a way to shorten out how the script knows when it’s clicking a TextButton.

My first attempt is bellow:

local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()

for _,v in pairs(script.Parent.Frame.TopBar:GetChildren()) do
	mouse[tostring(v)].Button1Down:connect(function(hit)
		print(hit)
	end)
end

However, I’m getting an error saying that the TextButton is not a valid member of PlayerMouse.

Any help would be appreciated! Thanks!

You are trying to find a child/property in the Mouse object with v's name. In this case, v's name would be ‘TextButton’ – so that’s why it’s throwing that error.

The only real issue with what you’ve done is that you’ve made it too complex – you’ve got the core theory right.

Put all of your TextButtons into one object, and loop through all of them, like you’ve done. But instead of using the mouse object at all, TextButtons have their own events which you can use instead:

TextButton.MouseButton1Down:Connect(function()
    print("Down!")
end)

Oh, duh. I’m not sure why I didn’t think of that. Thanks!

But, could you help me with the printing part of the script posted above? It’s printing out numbers.

I tried to do: print(tostring(hit))

But it’s still printing out numbers.

I want the script to print out the name of the object it’s clicking. What should I do to figure this out?

1 Like

You’d just print v.Name instead of tostring(hit).

It’s printing out numbers because of the arguments given in MouseButton1Down: http://robloxdev.com/api-reference/event/GuiButton/MouseButton1Down