Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How do I make a toggle script?

I've tried this code

paintBtn.Click:connect(function()
	if btnSelected == false then
		print("Plugin is now active")
		plugin:Activate(true) -- Neccessary to listen to mouse input
		gui.BTPaintToolGUI.Visible = true
		btnSelected = true
	end
	if btnSelected == true then
		print("Plugin is now inactive")
		plugin:Activate(false)
		gui.BTPaintToolGUI.Visible = false
		btnSelected = false
	end
	
end)

but it dosen't show any results, I click the button and nothing happens, it dosen't show, Output gives me this when i click the button Plugin is now active Plugin is now inactive at the same time. the exact same time. please help.

1 answer

It's unnecessary to have two ifs. The value is either false or true, so you can just use else to execute the other block. Use else! (Or at least elseif) when it's what you mean!


That actually fixes your bug.

Before the first if, selected could be true or false.

If it's false it becomes true in the first if.

... so when it gets to the second if, it's always going to be true.


You need the two branches to be mutually exclusive -- only one can happen. That's exactly what else is for!


Remark You're repeating yourself an awful lot!

if not btnSelected then
	print("Plugin is now active")
	btnSelected = true
else
	print("Plugin is now inactive")
	btnSelected = false
end
plugin:Active( btnSelected )
gui.BTPaintToolGUI.Visible = btnSelected

Does the same thing.

In fact, you can even cut out the repetition of setting btnSelected:

btnSelected = not btnSelected
if btnSelected then
	print("Plugin is now active")
else
	print("Plugin is now inactive")
end
plugin:Active( btnSelected )
gui.BTPaintToolGUI.Visible = btnSelected

This discussion is preserved as it was. New answers, comments, and votes are closed.