PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Create a Button to Toggle Text

Create a Button to Toggle Text

Jun 23 2018, 2:01 AM PST

Problem

You want to create a text button when once clicked, it will toggle its text.

Solution

Create a TextButton and connect the MouseButton1Down event.

local button, state = script.Parent, false
button.MouseButton1Down:connect(function()
	if state == false then
		button.Text = 'Hello World'
		state = true
	else
		button.Text = 'Click me!'
		state = false
	end
end)

Discussion

In order to use events with GUI we cannot control a GUI from one script, we must have a GUI for all the instances of the GUI. Therefore we’re going to have to build the GUI with Roblox Studio. While selecting the StarterGui click Insert -> Object -> ScreenGui, and then Insert -> Object -> TextButton. Now change all the properties of the TextButton as wanted. Be sure to change the Text property to the first state text “Click me!”. Then click Insert -> Object -> LocalScript inside of the TextButton and paste the solution code. Its a good idea to use LocalScript because it can give you helpful shortcuts in writing GUI that we will take advantage of later.

In the script we first connect a new GuiButton/MouseButton1Down|MouseButton1Down event to “button” (script.Parent because the script is inside the TextButton we access its parent to get to the TextButton itself) which fires when the left mouse button is down on the GUI. To do the toggling we use the “state” variable and just check if its false then set the text to one thing, otherwise set it to something else.

Tags:
  • gui
  • button