- Home /
Cursor Lock Not Working,Lock Cursor not Working
Hi, I'm new to Unity and I have been trying to get my cursor locked on the screen. I've followed a few tutorials and they all basically give me this code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HideCursor : MonoBehaviour
{
void Update()
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
}
The code does not work though. The cursor is invisible when on the screen, but I can move the cursor anywhere, even off the screen. Does anyone know the problem? Thanks.,I'm new to Unity and I am trying to lock my cursor, and I followed a few tutorials which all basically gave me this script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HideCursor : MonoBehaviour
{
void Update()
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
}
However this script is not working, the cursor becomes invisible when on the screen, but it is not locked and I can move it wherever. Does anyone know how to fix this? Thanks!
Answer by Stevens-R-Miller · Feb 24 at 04:01 PM
This is a change (with a bug) as of Unity 2020.3.26. In Unity 2018.2.14, this:
Cursor.lockState = CursorLockMode.Locked
does lock the cursor to the Game pane of the IDE when you enter play mode.
In 2020.3.26, it doesn't do so until you click in the Game pane. This leads to odd behavior because if you move the cursor over the Game pane in 2020.3.26, it becomes invisible, but it still interacts with element of the IDE outside the Game pane.
Answer by rage_co · Aug 17, 2021 at 01:15 PM
It's not a bug or problem of any kind...it's basically just how the cursor works in the unity editor...you can click in the game view to properly lock it and hit the escape key to unlock it, because y'know it'll be hard to do anything without the cursor in the editor.....don't worry this won't be there in the build
Answer by ChrisP999 · Apr 13 at 11:56 PM
I had this problem too, the trick was to use LateUpdate and with a flag so it only gets set once rather than on every frame. And search all your code for other calls to Cursor.lockState as it's probably being set somewhere else already and that will over-ride your code and make it fail the way you describe.
Your answer
Follow this Question
Related Questions
Cannot Hide Player 1 Answer
Public variable not appearing in the inspector (C#) 2 Answers
Hide mouse cursor 3 Answers
Displaying public variables in the inspector 2 Answers
Android re-hide status bar (Lollipop) 2 Answers