Cursor.lockState not working

Simple code I’ve got attached to an empty game object in my scene, however the cursor does not become confined in either the editor or a build. Here is the code:

void Start () {
		Cursor.lockState = CursorLockMode.Confined;
	}

void Update () {
	if (Input.GetKeyDown(KeyCode.Escape)) {
		if (Cursor.lockState == CursorLockMode.Confined) {
			Cursor.lockState = CursorLockMode.None;
		} else {
			Cursor.lockState = CursorLockMode.Confined;
		}
	}
}

I had some similar problems with 5.3.1p1 and I made the following observations:

  1. Transitioning from Locked to Confined does not work without first transitioning to None. The lockState will report correctly, but the behavior will be for the cursor to just jiggle in the center of the screen.

    Cursor.lockState = CursorLockMode.Locked;

    if (Cursor.lockState != CursorLockMode.Confined) {
    //Going directly from Locked to Confined does not work
    Cursor.lockState = CursorLockMode.None;
    Cursor.lockState = CursorLockMode.Confined;
    }

  2. Transitioning to Locked automatically hides the cursor

I know that this isn’t 100% the same as your problem, but I think the issue is at least semi-related and your question came up when I Googled the problem.

Try changing the Escape key to another button. Escape usually unlocks the cursor by default in the web player. And cursor doesn’t really work the way it should in the editor so if you want to test out cursors, you should usually try it on a build.

I’m using this…
Give it a try. Make sure to use “using System;” as library!

using UnityEngine;
using System.Collections;
using System;

public class GameMaster : MonoBehaviour {

	public bool lockCursor = true;


	void Awake () {
	
		Cursor.visible = (false);

	}


	void Update () {

		if(Input.GetKeyDown(KeyCode.M))
		{
			lockCursor = !lockCursor;
		}

		if (lockCursor) {
			Cursor.lockState = CursorLockMode.Locked;
		} else {
			Cursor.lockState = CursorLockMode.None;
		}
	}
}

This is old but here is how I Lock the Cursor when pressing Escape:

    if (Input.GetKeyDown("escape"))
    {
        StartCoroutine(DisableCursor());
    }

    private IEnumerator DisableCursor()
    {
        yield return new WaitForEndOfFrame();
        Cursor.visible = false;
        Cursor.lockState = CursorLockMode.Locked;
    }

None of the answers helped me, but later I found out this code works like a charm. Whenever u want to fix it, do a coroutine with FixMouse. Don’t know why this code works specifically for 2 * Time.deltaTime

    IEnumerator FixMouse ()
    {
        Cursor.lockState = CursorLockMode.Locked;
        yield return new WaitForSeconds ( Time.deltaTime * 2 );
        Cursor.lockState = CursorLockMode.Confined;
    }

void Start () 
{
    StartCoroutine ( FixMouse () );
}