- Home /
Trouble with Unity 4.6.1f1 Screen.lockCursor
I am trying to create a simple pause menu system (dubbed "pawsMenu" for in-game reasons) through a script attached to an empty GameObject seperate from the menu (a sort of universal GameController object, if you will) that allows for the user to press the "Cancel"/ESC key on the keyboard to simultaneously bring up the pause menu system in question by setting the GameObject it is parented to to be active, and also unlocking the mouse cursor through "Screen.lockCursor = false;". This all works just fine. I have created a function within this code that is called Continue() which essentially undoes the same steps used to bring up the pause menu: setting its parent GameObject to be inactive and re-locking the cursor.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class PawsMenu : MonoBehaviour {
public GameObject pawsMenu;
bool lockCursor = true;
bool showMenu = false;
void Update () {
pawsMenu.SetActive(showMenu);
Screen.lockCursor = lockCursor;
if(Input.GetButtonDown("Cancel")) {
if(showMenu == true && lockCursor == false) {
Continue();
}
else if(showMenu == false && lockCursor == true) {
showMenu = true;
lockCursor = false;
}
}
}
public void Continue() {
showMenu = false;
lockCursor = true;
}
public void MainMenu() {
Application.LoadLevel("MainMenu");
}
}
The problem I am running into is this: this Continue() function is normally called through the Unity UI button OnClick() system to close the pause menu in-game in order to continue playing. When the function is called in this way, it does exactly what I want it to do, closing the menu and locking the cursor again. But, if try to add the ability to call that same function from within the code by a press of the "Cancel"/ESC key when the menu is open and the cursor is not locked, in hopes to then close it in the same manner as mentioned previously, the menu will close as desired, but the cursor won't lock and stays visible. I don't understand why there would be a difference between the two ways of calling the same function and why only the line of code referring to the cursor locking would be affected by this change.
If anyone can help at all, I would REALLY appreciate it. Thanks.
Answer by AlwaysSunny · Apr 06, 2015 at 05:40 AM
This might be due to setting the active state of this object to false prior to making use of the lockCursor variable. Not sure whether the remainder of that Update function would execute after calling SetActive(false). Try moving the Screen.lockCursor line above the pawsMenu.SetActive line.
I dunno whether this is still a thing or not, but in previous versions, I recall it being necessary to set lock/hide every frame. Certain situations (like changes to application focus) seemed to reset these Screen properties. Just something to watch out for, I doubt it's the issue you're seeing here.