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

Join the Discord. Talk about Game Dev. Talk about Gaming.

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.

Join the Discord. Talk about Game Dev. Talk about Gaming.

Leave a Reply

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

You are commenting using your 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

Up ↑

%d bloggers like this: