Created
February 21, 2022 20:19
-
-
Save ciro-unity/2db7bde619596287bd801171d26c65e0 to your computer and use it in GitHub Desktop.
Simple script to lock/unlock the cursor in Unity using an input. Requires the "new" Input System package to work.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEngine.InputSystem; | |
public class CursorLocker : MonoBehaviour | |
{ | |
public InputAction lockCursorAction; | |
private bool _cursorLocked; | |
private void Start() | |
{ | |
lockCursorAction.Enable(); | |
//Setting it to initial state | |
_cursorLocked = Cursor.lockState == CursorLockMode.Locked; | |
} | |
private void OnEnable() => lockCursorAction.performed += OnActionPerformed; | |
private void OnDisable() => lockCursorAction.performed -= OnActionPerformed; | |
private void OnActionPerformed(InputAction.CallbackContext obj) | |
{ | |
ToggleCursorMode(!_cursorLocked); | |
} | |
private void ToggleCursorMode(bool newValue) | |
{ | |
_cursorLocked = newValue; | |
Cursor.visible = !_cursorLocked; //hiding/revealing | |
Cursor.lockState = _cursorLocked ? CursorLockMode.Locked : CursorLockMode.None; //locking/unlocking | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment