- Home /
Is mouse cursor over unity viewport (or get the true mouse position when it's outside of the viewport)
I have a camera controller script that I attach to a camera. That script is receiving input from the keyboard, mouse, and mouse wheel to handle WASD navigation, pretty much exactly in the same manner as the Unity Scene editor viewport we are all used to.
Unfortunately, my viewport is accepting input from the mouse wheel when the mouse is outside of the viewport.
I need a function
bool IsMouseOverViewport();
...to let me know if the mouse is over the Unity viewport, so that I can ignore inputs when the mouse is outside.
I have tried all sorts of combinations, but none of them work. I can read the mouse position properly, when the mouse is in the viewport, and I can check the bounds of the viewport to say, "yep I am in those bounds", but when the mouse moves outside of the viewport, every command I have tried to read the mouse position returns the last known position when it was in the viewport, not the actual mouse position that it is at.
For example, Debug.Log(Input.mousePosition); will NOT show negative numbers or even zero when I move the mouse to the left of the viewport.
The end result is that any function that I write always returns "true" no matter where the mouse cursor actually is.
Does anyone have a way to know if the mouse cursor is over our outside of the Unity viewport?