- Home /
How to detect mouse leaving / entering the game window?
Hi!
How can I tell when the mouse has left the window? Past answers have led me to:
OnMouseEnter / OnMouseExit, which appears to be limited UI elements with a specific width and height. I am not sure what element I'd attach this to--is there an element somewhere representing the screen?
// What object would I attach this to? void OnMouseEnter() { Cursor.visible = true; } void OnMouseExit() { Cursor.visible = false; }
Bounds checking on Update, which is failing me because Unity clips mousePosition to be inside the bounds of the window at all times (even if the mouse is outside). The code for this one:
void Update () { // Disable the hardware cursor while the mouse is inside the window Rect screenRect = new Rect(0, 0, Screen.width, Screen.height); Cursor.visible = screenRect.Contains(Input.mousePosition); }
The problem I'm trying to solve: I want a software cursor I control, so I want to disable the hardware cursor while the mouse is inside my window, and reenable when it exits. It's very difficult to work in Unity when the cursor is disabled :)
Thanks!
--John
Guessing you saw this one :
http://answers.unity3d.com/questions/474825/how-to-restrict-mouse-going-off-screen.html
Yep, that one advocates using mouse position, which isn't working for me due to the fact that that position is never given a value out of bounds--it is clipped to window width and height.
Unfortunately, from what I've searched for, Unity doesn't have such option just like it doesn't have any event that triggers when window is being moved(causes game to freeze without any warnings - especially bad in multiplayer), resized(makes us check Screen.width/height in Update) and such. All of them are OS based events.
Didn't test it, but maybe you can lock cursor to screen and unlock it when it's on edge (or somewhere near edge) simulating needed behaviour? And locking back when it's inside again.
Answer by eviljake29 · Feb 07, 2016 at 05:55 PM
Right click in the hierarchy and create an empty
Attach the first script to that
void OnMouseEnter()
{
Cursor.visible = false;
}
void OnMouseExit()
{
Cursor.visible = true;
}
And you have to switch the Boolean values around...
before it turned the cursor on when it entered the window.
Your answer
![](https://koobas.hobune.stream/wayback/20220612063129im_/https://answers.unity.com/themes/thub/images/avi.jpg)