- Home /
Trying to use toggle as checkbox that only gets called once on click.
I'm trying to use toggle as a checkbox that only gets called once. The checkbox should display on start, and continue to display after it is clicked. On click I want it to change state, and then perform an action only once. That action should differ, depending on whether that state is checked or unchecked.
Here is my code.
public bool checkBoxClicked = true;
public bool checkBox = false;
void OnGUI()
{
public bool checkBoxClicked = true;
public bool checkBox = false;
if (checkBoxClicked == true)
{
checkBox = GUI.Toggle(new Rect(25, 25, 100, 30), checkBox, "checkBox");
checkBoxClicked = false;
Debug.Log("Inside if");
}
This code does not display the toggle, but it does output "Inside if" to the console.
Answer by Key_Less · Dec 05, 2013 at 10:35 PM
The problem is you're setting the checkBoxClicked and checkBox flags to true every time OnGUI() is called so your if condition will always evaluate to true. If you remove the checkBoxClicked and checkBox initializations from OnGUI() then your toggle should work.
Answer by Fragmental · Jan 06, 2014 at 10:55 AM
Here is the what I ended up with. Thanks for the help.
public bool checkBoxClicked;
public bool checkBox = false;
void OnGUI()
{
checkBoxClicked = GUI.Toggle(new Rect(25, 25, 100, 30), checkBox, "checkBox");
if (checkBoxClicked != checkBox)
{
checkBox = checkBoxClicked;
if (checkBox == true)
Debug.Log("Box is Checked");
else if (checkBox == false)
Debug.Log("Box is not checked");
}
}