Skip to content

Instantly share code, notes, and snippets.

@ciro-unity
Created February 21, 2022 20:19
Show Gist options
  • Save ciro-unity/2db7bde619596287bd801171d26c65e0 to your computer and use it in GitHub Desktop.
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.
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