How To Detect Any Key Press But Ignore Mouse – Unity C#

There might be a time you want to check if the player has pressed any key on the keyboard – but you do not want Unity to check for mouse clicks. This can be frustrating, because for some reason, the line of code you would expect to work checks for both keyboard presses AND mouse clicks:

if (Input.anyKeyDown)
{ ... }

I don’t know why Unity didn’t separate out mouse clicks and keyboard presses into two separate lines of code, but there it is. This is something I frequently had to fight Unity about while developing Puzzledorf, particularly when designing the menu’s and the title screen.

How To Do It

Fortunately, the workaround is simple:

    private void Update()
    {
        if (Input.anyKeyDown && !(Input.GetMouseButtonDown(0) 
            || Input.GetMouseButtonDown(1) || Input.GetMouseButtonDown(2)))
        {
            Debug.Log("No mouse pressed!");
        }
    }

The solution is a slightly more complicated if statement. First we check if any key is down, including mouse clicks, but then we also make sure that none of the mouse buttons are being pressed.

If you are confused by what &&, || and ! mean in the if statement, read my article here explaining them.

Leave a comment

Blog at WordPress.com.

Up ↑