how to stop mouse going out of the screen ?

Hi, guys i was wondering if you could please help me. Basically the problem that i am having is with my mouse cursor. what i want to do is if the player runs the game in the build view and his window is in not in full mode i want to stop them from leaving the screen. so what i mean is when ever you make a build and run it you can always get you mouse cursor out of the screen and start touching the X button and Minimize and etc. So what i want to do is if the game starts the mouse is hidden and if they try to go out of the screen i don't want that to happen. Unless they pause the game and the mouse cursor will go back the way it was.

here what i have come up with so far dont laugh lol i will be really happy if some one could really help me :-) thanks in advance MCHALO :)

My script:

    function Awake()
   {

    Screen.showCursor = false;

   }

I know this is an old answer, but it helps to keep old answers update with current information. I found a much easier and up to date solution:

Cursor.lockState = CursorLockMode.Confined; // keep confined in the game window
Cursor.lockState = CursorLockMode.Locked;   // keep confined to center of screen
Cursor.lockState = CursorLockMode.None;     // set to default default

I found a better solution for this problem using PInvoke. This would work only on windows, but windows is the main platform that suffers from this problem I believe:

#if UNITY_STANDALONE_WIN
    [DllImport("user32.dll")]
    static extern bool ClipCursor(ref RECT lpRect);

    public struct RECT
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }
#endif

public void Start()
{
    RECT cursorLimits;
    cursorLimits.Left   = 0;
    cursorLimits.Top    = 0;
    cursorLimits.Right  = Screen.width  - 1;
    cursorLimits.Bottom = Screen.height - 1;
    ClipCursor(ref cursorLimits);
}

All you can do is use Screen.lockCursor to lock the cursor in the center of the screen and hide it. Don't just do it in your Awake function because if a player presses escape you'll have to reinitialise it. Do it OnMouseDown possibly.

As far as I know you cannot restrict the mouse from going outside the window of the application. However as stated above it is possible to lock the cursor to the center of the screen.

http://unity3d.com/support/documentation/ScriptReference/Screen-lockCursor.html

At this point you will have to draw your own cursor and handle your own cursor events. You can still calculate the position of the cursor using Input.GetAxis(“Mouse X”) and Input.GetAxis(“Mouse Y”) assuming they are configured in Project Settings->Input. You will likely have to detect mouse button clicks using Input.GetMouseButtonXXXX().

Just to give an update, since this topic is out of date but still high on search results, you should use:
Cursor.lockState = CursorLockMode.Confined;

This has been available since at least Unity 5.2.

what about:

Screen.lockCursor = true;

i wold put this in function start and ad to the update a button to release it

I solved this for myself with the help of an Asset Store asset called ProMouse, which let’s you set the mouse position. The script below uses that asset, toggles control with the escape key, and stops movement with Time.timeScale while cursor isn’t controlled. You have to click inside the game window, then hit escape to get things going again.

// ****** code for ProMouseControl.cs 
using UnityEngine;
using System.Collections;

public class ProMouseControl : MonoBehaviour {

	private bool controlMouse;
	
	void Start () {
		ProMouse.Instance.SetCursorPosition(Screen.width/2, Screen.height/2);
		controlMouse = true;
	}

	void Update () {
		int mouseX = (int)ProMouse.Instance.GetLocalMousePosition().x;
		int mouseY = (int)ProMouse.Instance.GetLocalMousePosition().y;
		if (controlMouse) {
			if ( mouseX <0) {
				ProMouse.Instance.SetCursorPosition(0,mouseY);
			}
			if ( mouseX > Screen.width) {
				ProMouse.Instance.SetCursorPosition(Screen.width,mouseY);
			}
			if ( mouseY <0) {
				ProMouse.Instance.SetCursorPosition(mouseX,0);
			}
			if ( mouseY > Screen.height) {
				ProMouse.Instance.SetCursorPosition(mouseX, Screen.height);
			}
			if (Input.GetKeyUp("escape") ) {
				Time.timeScale = 0;
				controlMouse = false;
			}
		} else if (Input.GetKeyUp("escape") ) {
			Time.timeScale = 1;
			ProMouse.Instance.SetCursorPosition(Screen.width/2, Screen.height/2);
			controlMouse = true;
		}
	}
}

Hi,all my projects using cursorLocked are stucked. The mouse stay there shaking at the right of the gamescreen. There has been two upgrades before this problem happens. i upgraded to unity 2019.2 and My windows 10 upgraded to ver 1903
Nothing goes well anymore, and i don’t know how to remediate.

Here is the simple code that was still working last week…

void Start()
{
     Cursor.visible = false;
     Cursor.lockState = CursorLockMode.Locked;
}

private void OnMouseDown()
    {
             Cursor.visible = true;
             Cursor.lockState = CursorLockMode.None;
     }

This is quite a bit old, but nonetheless, My issue was the mouse wouldn’t lock after minimizing the engine, and coming back to it, while it was in play mode.

I found the answer to why it was happening to me, Here

Basically what was going on was, I didn’t have the option: “Run in background” enabled in the player settings.

This may also help others that are running into this as well; or at least can check it off the list of possible fixes.

Wow. Lots going on here. If you have PlayMaker installed and PlayMakerGUI in your hierarchy it defaults to controlling the mouse cursor. Untick the box in the inspector that says ‘Control Mouse Cursor’.