How to turn on and off a bool with a button press

Dirt simple problem: I need a bool to switch back and forth when a single button is pressed. In my case the trigger on an Xbox controller.

 void Start () {
        crawlCheck = false;
    }

void Update () {
        isCrawling = Input.GetAxis("Crawl Toggle");

        if (isCrawling == 1 && crawlCheck == false)
        {
            crawlCheck = true;
        }

        else if (isCrawling == 1 && crawlCheck == true)
        {
            crawlCheck = false;
        }
    }

I just need crawlCheck to change to false or true when the trigger is pressed and stay there until it’s pressed again.

What I get is it switching from true to false and back as long as the trigger is held.

You can toggle the value of a boolean by using the “not” operator:

  • not true = false
  • not false = true

So you can write something like this to toggle it back and forth;

if (your button is down)
{
    crawlCheck = !crawlCheck;
}

I’m a little confused by this thread guys, referring to the last message Dave, you said that you generally use the Input.GetButtonDown, but then you never used it in your example?

It may have made more sense if you did use GetButtonDown, because what does the GetAxis have to do with pushing a button? (I’m noob to code trying to learn)
when you followed GetAxis, you did so with “Crawl Toggle” but this is a variable which you haven’t declared previously? This code really confused me :slight_smile:

What is the best way to do this please?

thankyou

Use properties instead of fields:
public bool check; → public bool check {get;set;}
In the button component:
Select “check” property in your script