Reputation: 29
I am making a FPS Game. So, when I start the game, the cursor is locked and I can not see it. When I press Escape key, now, I am able to see the Cursor and I can move it around and interact with it on my screen and I can not control the game camera now. That is fine. Now, I press Escape key again, and now, I can resume controlling the camera in game, but I can still see the cursor and I can move the camera in game while making the cursor interact with all the stuff even outside of my game window.
The Code
void Update()
{
LockAndUnlockCursor();
if(Cursor.lockState == CursorLockMode.Locked)
{
LookAround();
}
}
void LockAndUnlockCursor()
{
if(Input.GetKeyDown(KeyCode.Escape))
{
if(Cursor.lockState == CursorLockMode.Locked)
{
Cursor.lockState = CursorLockMode.None;
}
else if (Cursor.lockState == CursorLockMode.None)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
}
}```
Upvotes: 0
Views: 144
Reputation: 547
In the editor this tends to bug out, you have to constantly set it in Update() by saving them into variables.
bool isCursorLocked;
Update() {
if (Input.GetKeyDown(blah))
isCursorLocked = !isCursorLocked;
if (isCursorLocked)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
else
{
// etc
just use variables and always set the cursor lock every Update(). If you don't want this code running always then you could use #if UNITY_EDITOR in a way to only set it every single update for unity editor
Upvotes: 1