I need some help with this small snippet of code that I have made, as it doesn’t work as intended, I can access it from the inspector and when isOn is set to true, I can manually inable it in the inspector, but otherwise it doesn’t work.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InGameMenu : MonoBehaviour
{
public GameObject Options;
public bool isOn = false;
void Start()
{
}
void Update()
{
if (Input.GetKeyDown("a") && isOn == false)
{
isOn = true;
}
if (Input.GetKeyDown("a") && isOn == true)
{
isOn = false;
}
if (isOn == true)
{
Options.SetActive(true);
}
if (isOn == false)
{
Options.SetActive(false);
}
}
}
Hi!
It’s because your code has next execution cycle:
- When you press A and isOn is false we swap it to true;
- After that since we pressed in this frame button A and already swapped isOn to true then the next if statement will be true as well and swap isOn boolean back to false;
- Options stays false since we swapped boolean back to false.
When your code have mutually exclusive things you should use “else if” because that prevents one statement from execution when the other is executed:
if (Input.GetKeyDown("a") && isOn == false)
{
isOn = true;
}
else if (Input.GetKeyDown("a") && isOn == true)
{
isOn = false;
}
if (isOn == true)
{
Options.SetActive(true);
}
else if (isOn == false)
{
Options.SetActive(false);
}
And you can even do this way:
if (Input.GetKeyDown("a") && isOn == false)
{
isOn = true;
Options.SetActive(true);
}
else if (Input.GetKeyDown("a") && isOn == true)
{
isOn = false;
Options.SetActive(false);
}
Since there is no reason for checking each frame the isOn boolean.
Another way of simplification is this:
if (Input.GetKeyDown("a"))
{
isOn = !isOn;
Options.SetActive(isOn);
}
Basically, we just swap isOn to the opposite of current isOn and SetActive your Options accordingly to the current isOn state.
Hope it helps.
Do remember that whenever a key is pressed, its effects last throughout the frame. When a is pressed, according to flow of control, first condition is met and isOn is set to true. But as the code execution moves forward and next condition is reached then since button presses last for complete frame, that condition is also met as button is pressed and isOn is also true. So condition is met and isOn is set to false again.
You should try to use else if in : if (Input.GetKeyDown("a") && isOn == true) { isOn = false; }
.
That is if first condition is met then dont execute the second one.
After correcting your code, whenever you press a key, isOn is set to a value opposite to that of it was earlier. And the other condition is ignored so that isOn is not set to its earlier value.
@TheBossPugs