- Home /
Why isn't Cursor.lockstate = cursorlockmode.locked; working?
I've been following a Brackeys tutorial for first person movement and have followed the code exactly. It uses cursor lockstate to lock the cursor to the center of the screen, but when I run the game, it doesn't work. The cursor is hidden when it's within the game window, but as soon as it gets further, it reappears, meaning that cursor lock mode isn't working. Does anyone know how to get it to work? I know there are other questions on unity answers about this same thing, but I've reviewed them and none of them are helpful. They are either outdated, or saying "use cursor.lockstate = cursorlockmode.locked" instead of the outdated methods. Here is the code:
using System.Collections; using System.Collections.Generic; using System; using UnityEngine; public class MouseLook : MonoBehaviour { public float MouseSensetivity = 250.0f; public Transform playerBody; float xRot = 0f; // Start is called before the first frame update void Start() { Cursor.lockState = CursorLockMode.Locked } // Update is called once per frame void Update() { float mouseX = Input.GetAxis("Mouse X") * MouseSensetivity * Time.deltaTime; float mouseY = Input.GetAxis("Mouse Y") * MouseSensetivity * Time.deltaTime; xRot -= mouseY; xRot = Mathf.Clamp(xRot, -90f, 90f); transform.localRotation = Quaternion.Euler(xRot, 0f, 0f); playerBody.Rotate(Vector3.up * mouseX); if (Input.GetKey(KeyCode.Tab)) { Cursor.lockState = CursorLockMode.None; } } }
Answer by Bradwall · Jul 10, 2021 at 09:06 PM
I don't know why this works, but I tried clicking the window and now the code works completely. I would archive this or delete the question, but I'm curious, does anyone know why this works?
its actually a feature in unity editor to allow us to work and tweak values even when we're in the game mode.....like pressing esc will automatically disengage the cursor....if you build the project, no such problem will be there
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Method to stop enemies from spawning Unity5 0 Answers
Dynamic EditorGuiLayout.PopUp list 1 Answer