- Home /
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;
}
}
}
Answer by saschandroid · Oct 26, 2015 at 12:48 PM
else if (Input.GetKeyDown(KeyCode.I) && controls == false)
{
controls = true;
}
Ill check if that fixes it, but I don't understand why that should work, and why $$anonymous$$e doesn't.
In the same frame (Update function) you set controls to false in the first 'if', but the second 'if' is called too (because controls is now false and Input.Get$$anonymous$$eyDown() still is true - same frame) and therefor controls is set back to true. That means the controls variable can never be false at the end of the frame and alpha will never be 0.
Answer by Styla · Oct 26, 2015 at 03:06 PM
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,