Cursor lock frozen response

I’ve got the following code for toggling between the cursor lock:

    public bool lockCursor;

    void Start () {
        lockCursor = true;
    }

    void Update () {
        if (Input.GetKeyDown (KeyCode.Escape)) {
            lockCursor = !lockCursor;
        }
        if (lockCursor == false) {
            Cursor.lockState = CursorLockMode.None;
        }

        else {
            Cursor.lockState = CursorLockMode.Locked;
        }
    }

And it works, as in the bool is toggling on/off when I click the “Esc” key. But when I click it again, the cursor only becomes locked if I click on the game screen.

Is this just an editor/engine thing, and will be work properly when I “build” the game? Or am I doing something wrong?

Edit: I know that by default, Unity will unlock the mouse if you press “Esc”. Could this be causing it? If so, how do I prevent that from happening?

Bump.

Unity’s editor overrides hiding and locking the cursor. It’ll work properly once you build the game.

1 Like