- Home /
LockCursor script not working as intended
I wrote a very simple script which hides and locks the mouse when escape is pressed and unlocks it and shows is back when pressed again. The issue is that sometimes it hides it when it is pressed and sometimes it doesn't. The same goes for the showing. I have no idea where the problem is.
private bool isCursorLocked;
void Start ()
{
isCursorLocked = true;
}
void CheckCursorStatus()
{
if (isCursorLocked) {
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
} else {
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
}
/*
************************** GUI Functionality **************************
*/
void CheckMenuInput()
{
if (Input.GetAxis("Menu") > 0) {
if (isCursorLocked) {
isCursorLocked = false;
} else {
isCursorLocked = true;
}
}
}
void Update ()
{
CheckMenuInput();
CheckCursorStatus();
}
Answer by ShadyProductions · Jun 02, 2017 at 08:53 AM
if (isCursorLocked) {
isCursorLocked = false;
} else {
isCursorLocked = true;
}
can be simplified to
isCursorLocked = !isCursorLocked
also because you use (Input.GetAxis("Menu") > 0) {
it will constantly trigger this each frame in update which might give u weird effects, while if u use something like GetKeyDown it will only trigger once, when the key is pressed for the first time initially.
Replacing GetAxis with Get$$anonymous$$eyDown worked. I wish I had tried that myself, but I thought the problem was not co$$anonymous$$g from there. Thank you!
Answer by SrGonzalez · Jun 02, 2017 at 08:52 AM
try to add this line to your start function:
void Start ()
{
isCursorLocked = true;
CheckCursorStatus(); //this will execute the check fucntion
}
Answer by Lili-Shi · Jun 07, 2017 at 01:38 PM
Have you tried this functionality on a built version of your game, or just in the editor?
Being in the Editor and setting the Cursor.lockState to CursorLockMode.Locked (which btw should automatically turn the cursor invisible), and then pressing Escape will result in the Editor resetting the Cursor.lockState, however having the game built, the Cursor.lockState set to CursorLockMode.Locked and then pressing Escape won't "release" the cursor, unless you explicitely code that in.
And to answer your implicit question beforehand: As I glanced through your script, I can say, that it look's fine on first glance.