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:

  1. 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;
    }

  2. 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 :slight_smile:

Thanks!

–John

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.