On/Off Toggle UI Script

Alright so, I’ve been trying to Script an On/Off type of System for my Game’s Settings, and even though I tried so many scripts and also looked it up online unsuccessfully, I’m unsure of what to do. As you can tell, I’m a really beginner Scripter, and I need your help on this.

This is the current state of the script that I hoped would work, but doesn’t:

script.Parent.MouseButton1Click:Connect(function()
	if script.Parent.Text = "OFF" == true then
		script.Parent.Text = "ON"
	end
	if script.Parent.Text = "OFF" == false then
		script.Parent.Text = "OFF"
	end
end)

(That might be the current Script, but once I make it work, I’ll also add a TextColor3 change.) I’ve also tried using a Bool Value based on another related Post on the DevForum, but very unsuccessfully obviously. What do you think I should fix in that Script?

1 Like
script.Parent.MouseButton1Click:Connect(function()
	if script.Parent.Text == "OFF" then
		script.Parent.Text = "ON"
	elseif script.Parent.Text == "ON" then
		script.Parent.Text = "OFF"
	end
end)

A brief way:

script.Parent.MouseButton1Click:Connect(function()
     script.Parent.Text = if script.Parent.Text == "OFF" then "ON" else "OFF"
end)

--Thanks for @EmbarTheHybrid for reminding this method

[You’d have to play with this one]

Here is the Ternary version:

local text = script.Parent

script.Parent.MouseButton1Click:Connect(function()
	local NewText = text.Text == "ON" and "OFF" or "ON"
	text.Text = NewText
end)
3 Likes

You replied really fast with a solution for my problem, thanks, it means a lot for me :happy3:

I know a solution has alreayd been declared, but you can also do this as a one liner using the ternary operator

script.Parent.MouseButton1Click:Connect(function()
	script.Parent.Text = if script.Parent.Text == "OFF" then "ON" else "OFF"
end)

If that doesn’t work you can try

script.Parent.MouseButton1Click:Connect(function()
	script.Parent.Text = script.Parent.Text == "OFF" and "ON" or "OFF"
end)

As I haven’t yet messed around with the new Ternary operator they’ve given to LuaU

1 Like

Here is how you could use Ternary here-

local text = script.Parent

script.Parent.MouseButton1Click:Connect(function()
	local NewText = text.Text == "ON" and  "OFF" or text.Text == "OFF" and "ON"
	text.Text = NewText
end)

It works for me

1 Like

That looks like a more complicated version of

text.Text == "ON" and "OFF" or "ON"

1 Like

Oops, my bad.

Guess I was in a rush that I didnt notice
Thanks again for the correction

1 Like
local text = script.Parent

text.MouseButton1Click:Connect(function()
	text.Text = if text.Text == "ON" then "OFF" else "ON"
end)

May as well use ‘text’ instead of ‘script.Parent’ since it has already been declared.