Toggling with a key not working

Hey everyone, I’ve written a script that should toggle the UI, unfortunately I have no idea why it is not working.
It works when toggling from off to on, but not on to off.

public class intro : MonoBehaviour {
    public bool controls;
    CanvasGroup canvas;
	// Use this for initialization
	void Start () {
    canvas = GetComponent<CanvasGroup>();
    controls = true;
	}
	
	// Update is called once per frame
	void Update () {
        if (Input.GetKeyDown(KeyCode.I) && controls == true)
        {
            controls = false;
        }
        if (Input.GetKeyDown(KeyCode.I) && controls == false)
        {
            controls = true;
        }  
        if (controls == true)
        {
            canvas.alpha = 1;
        }
        if (controls == false)
        {
            canvas.alpha = 0;
        }
	}
}

Hi,

Not pretty sure about my answer but I think the problem is that you put your key directly in the void update function.

So when you toggle from off to on , there is no problem because controls == false and it fires normally.

From the other side, it will read the code completly.

 if (Input.GetKeyDown(KeyCode.I) && controls == true)
         {
             controls = false;
         }
         if (Input.GetKeyDown(KeyCode.I) && controls == false)
         {
             controls = true;
         }  

If I recap, the input “I” will be down so controls will be true so it will put controls to false.
Just after the input will be still down ( same frame so the instruction will also fire )
so it will enter the if (Input.GetKeyDown(KeyCode.I) && controls == false)
so controls will be true again.

Try to put your if on the other side and you will know how to correct your mistake.

Best regards,

else if (Input.GetKeyDown(KeyCode.I) && controls == false)
{
controls = true;
}