Toggle Boolean by Input.getKey like if pressed one time true next time false and so on.

Hello All,

I want a Toggle Boolean by using Input.getKey(i don’t want it by keydown) like if pressed one time true next time false and so on.
I have tried the code but it gives weird result. here is the code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    public bool suri;

    void Update()
    {
        if(Input.GetKey(KeyCode.A))
        {
                suri=toggle(suri);
        }        
    }
     public static bool toggle(bool suri)
    {
     return !suri;
    } 
    
}

I haven’t tried the following code

 public class NewBehaviourScript : MonoBehaviour
 {
     public bool suri;

     private bool isPressingKey;

     private bool IsPressingKey
     {
         get { return isPressingKey; }
         set
         {
             if(value == isPressingKey)
                return;

            isPressingKey = value;

            // isSuri will be toggled when the key gets pressed down
            // if you want the boolean to be toggles when the key is released
            // change the condition to `if(!isPressingKey)`
            if(isPressingKey)
                suri = !suri;
         }
     }
 
     void Update()
     {
         IsPressingKey = Input.GetKey(KeyCode.A);
     }
 }

However, it’s tedious. Maybe the new Input System could solve your issue in a more elegant way.

Thank you for your reply.

@Babish8 and @Hellium i am working on physical joystick which don’t have button up function.
It only have boolean, which onpress become true else false.

I want to have a toggle function on that button. so i cant use GetKeydown.

@AhmedElshazly i have tried this but it changes too fast and sometime don’t work.

Thanks Everyone, for all the solutions.

@Hellium you are right, your solution works special thanks to you.

Try Using this
if(Input.GetKey(KeyCode.A))
{
suri = !suri;
}

Here is my ‘5 cents’

BTW I’m not sure but I guess that if you use only GetKey (instead of GetKeyDown) it will keep calling the code inside untill you hold the key. so try it with GetKeyDown instead


public bool isActive = false;

private void Update()
{
     if(input.GetKey(KeyCode.A))
     {
          isActive = !isActive;
          //more code here
     }
}