I found this code online once and I’m trying to put in some lines that can relock the cursor but it isn’t working. Any help?
using UnityEngine;
using System.Collections;
public class CursorLock : MonoBehaviour {
// A boolean to check if the cursor is locked.
bool IsLocked;
void Start () {
// The mouse is invisible when the game is started.
Cursor.lockState = CursorLockMode.Locked;
// The cursor is locked.
IsLocked = true;
}
void Update () {
// To see the mouse again after pressing a certain key.
if (IsLocked == true){
if(Input.GetKeyDown("escape")){
// The cursor is freed!
Cursor.lockState = CursorLockMode.None;
// A boolean for relocking.
IsLocked = false;
}
}
// To relock the cursor.
if(IsLocked == false){
if(Input.GetKeyDown("escape")){
// The cursor is locked!
Cursor.lockState = CursorLockMode.Locked;
// The boolean again.
IsLocked = true;
}
}
}
}
I can unlock my cursor, but I can’t re-lock it. Btw I followed you advice and changed my code:
void Update () {
// To see the mouse again after pressing a certain key.
if (Input.GetKeyDown("escape")){
if(IsLocked){
// The cursor is freed!
Cursor.lockState = CursorLockMode.None;
// A boolean for relocking.
IsLocked = false;
}
else {
// The cursor is locked!
Cursor.lockState = CursorLockMode.Locked;
// The boolean again.
IsLocked = true;
}
}
}
Oh, neat… I found what someone mentioned the other day in a similar thread. An editor issue with locking the Cursor!
That day, I thought it was working (but we were also hiding the cursor).
He suggested to build and test… I thought of that for your issue, because it didn’t work for me, either, but building the project did work