0
\$\begingroup\$

To understand the difference, let me review a bit about the behavior of GetKeyUp and GetKeyDown with the following code snippet.

void Update()
{
    if (Input.GetKeyDown(KeyCode.Escape))
    {
        Debug.Log("Escape Key Down");
    }

    if (Input.GetKeyUp(KeyCode.Escape))
    {
        Debug.Log("Escape Key Up");
    }
}

Right after pressing the Esc key (and holding it), a message "Escape Key Down" is produced. Later right after releasing the key, a message "Escape Key Up" will show. The behavior does make sense.

Now I apply this for toggling (locking/unlocking) the mouse cursor. Here is my code snippet.

void Update()
{

    if (Input.GetMouseButtonDown(0))
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    if (Input.GetKeyUp(KeyCode.Escape))
    {
        Cursor.lockState = CursorLockMode.None;
        Cursor.visible = true; 
    }
}

Right after clicking the left mouse button, the cursor becomes invisible. However, right after pressing down the Esc key, the cursor becomes visible again. The expected behavior is that the cursor will be visible right after releasing the Esc key rather than right after pressing the key.

Question

How to fix this abnormal behavior?

\$\endgroup\$
3
  • \$\begingroup\$ Doesn't pressing the escape key always break out of cursor lock, even if you delete your GetKeyUp code block entirely? \$\endgroup\$
    – DMGregory
    May 7 '20 at 11:20
  • \$\begingroup\$ Ah, if that turned out to be the solution, post it as an Answer. It might help others. :) \$\endgroup\$
    – DMGregory
    May 7 '20 at 11:31
  • \$\begingroup\$ You're welcome to, since you're the one who's tested it first-hand. \$\endgroup\$
    – DMGregory
    May 7 '20 at 11:40
1
\$\begingroup\$

DMGregory's comment is the answer.

Doesn't pressing the escape key always break out of cursor lock, even if you delete your GetKeyUp code block entirely?

So I have to change Escape key to another key to avoid this problem.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.