What am I doing wrong with this bool?

Hi guys, so I’m trying to make a flashlight for my game and the logic is: if the Player presses “f” and the flashlight is off, it will turn on, and likewise in the other way around.

The code is like this:

if (Input.GetKeyDown("f"))
        {
            FlashOn = true;
         }

if (FlashOn && Input.GetKeyDown("f"))
        {
            FlashOn = false;
        }

When I run it and press “f” , the bool FlashOn is checked, but when I press it again it doesn’t uncheck, like I intended ;-;

Is my logic wrong or am I making a coding mistake? If you guys could help me it would be much appreciated :slight_smile:

if (Input.GetKeyDown(“f”)) //first check the input, then act on it
{
if (!FlashOn) //if off
{
FlashOn = true; // turn on

			{
			else // if on
			{
			   FlashOn = false; //turn off
			}
          }

When you press “f” the script is first told to set FlashOn to true. Then the script is told to set FlashOn to false if the “f” key is pressed (which it is) and if FlashOn is true which it is since you just told it to. This leads to the bool always being false since every time you press the button it is first set to true and then set to false. I do not understand why it would always be true, like you mentioned. Either way. One way to fix this is to make the first if statement an else if statement of the second if statement.
What I mean:

if (FlashOn && Input.GetKeyDown("f"))
        {
            FlashOn = false;
        }
        else if (Input.GetKeyDown("f"))
        {
            FlashOn = true;
        }

But since you want to toggle the flashlight I would recommend you to also just toggle the bool. This is what I mean by that:

if (Input.GetKeyDown("f"))
        {
            FlashOn = !FlashOn;
        }

Now, each time you press “f” the bool will be set to what it is not.

Thank you very much guys, it worked! :slight_smile: