When the game is started the first 2 times pressing M returns false in the debug log and then the code flips between true and false. Is there a reason I have to press M twice in order for the code to then enable the cursor the first time?
private void Awake()
{
UnityEngine.Cursor.visible = false;
UnityEngine.Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.M))
{
if (UnityEngine.Cursor.visible == true)
{
Debug.Log("true");
UnityEngine.Cursor.visible = false;
UnityEngine.Cursor.lockState = CursorLockMode.Locked;
}
else if (UnityEngine.Cursor.visible == false)
{
Debug.Log("false");
UnityEngine.Cursor.visible = true;
UnityEngine.Cursor.lockState = CursorLockMode.None;
}
}
Input.GetKeyDown(KeyCode.M) returns a bool value, your code is stating:
if(Input.GetKeyDown(KeyCode.M) == true) then the second if(UnityEngine.Cursor.visible == true) meaning your code is asking is if the keycode is pressed AND the cursor is visible, if not is the keycode pressed AND the cursor is not visible.
Look into ternary operation for your cursor which makes that bit easier, and consider which bool is activated on the first press (think of it as a lightswitch it is on or off. if it is already on (true) pressing it turns it off (false) pressing again makes it on again (true)
The inner if statements are somewhat unnecessary. You can just flip the visible boolean, and use that to determine the lock state:
private void Awake()
{
UnityEngine.Cursor.visible = false;
UnityEngine.Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.M))
{
bool flippedVisible = !UnityEngine.Cursor.visible;
UnityEngine.Cursor.visible = flippedVisible;
if (flippedVisible == true)
{
UnityEngine.Cursor.lockState = CursorLockMode.Locked;
}
else
{
UnityEngine.Cursor.lockState = CursorLockMode.None;
}
}
}
I tried your code but the cursor wouldn’t change between visible and invisible even though flippedVisible was changing.
I changed my code to have check for when m is pressed and if the cursor is visible. That fixed the issue of having to press m twice in order to change the cursor to visible the first time. Wasn’t the original code doing the same thing but with another if statement? I’m very curious to know what caused the issue.
If statements are sequential meaning that the first IF statement must return its value (true or false) then move onto the next in the line etc. There are several ways to deal with this, ternary operators, multi-conditioned if statements etc.