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.

If you enjoyed reading, try my game Puzzledorf out on Steam and Humble Bundle.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: