Skip to content

Instantly share code, notes, and snippets.

@SteveSwink
Created February 17, 2015 14:07
Show Gist options
  • Save SteveSwink/7036700cc1c665b5f660 to your computer and use it in GitHub Desktop.
Save SteveSwink/7036700cc1c665b5f660 to your computer and use it in GitHub Desktop.
LockCursor
using UnityEngine;
using System.Collections;
public class LockCursor : MonoBehaviourSingleton<LockCursor> {
public bool lockCursor = true; // Set this to enable/disable the lock.
CursorLockMode mode;
void Update()
{
if (Screen.lockCursor != lockCursor)
{
// if the pause menu is open, cursor no locky and bail out of update
if(PauseMenuScale.Instance.paused){
// Debug.Log("pause menu thinks it's active");
// Screen.lockCursor = false;
Cursor.lockState = CursorLockMode.Confined;
return;
}
if (lockCursor && Input.GetMouseButton(0)){
// Screen.lockCursor = true;
Cursor.lockState = CursorLockMode.Locked;
}
else if (!lockCursor){
Cursor.lockState = CursorLockMode.Confined;
// Screen.lockCursor = false;
}
}
}
void SetCursorState (CursorLockMode newMode)
{
mode = newMode;
Cursor.lockState = newMode;
// Hide cursor when locking
Cursor.visible = (CursorLockMode.Locked != newMode);
}
public void SetCursorLocked(){
Debug.Log("LOCK THE CURSOR at " + Time.timeSinceLevelLoad);
SetCursorState(CursorLockMode.Locked);
lockCursor = true;
StartCoroutine(SetCursorStateDelayed(mode, 100));
}
public void SetCursorUnlocked(){
Debug.Log("UNLOCK THE CURSOR at " + Time.timeSinceLevelLoad);
lockCursor = false;
SetCursorState(CursorLockMode.Confined);
}
public IEnumerator SetCursorStateDelayed(CursorLockMode newState, int framesToDelay){
int frame = 0;
while(framesToDelay > frame){
frame++;
// Debug.Log("Yield a frame in LockCursor at " + Time.timeSinceLevelLoad);
yield return 0;
}
Cursor.lockState = newState;
}
public IEnumerator SetCursorStateDelayed(bool newState, int framesToDelay){
int frame = 0;
while(framesToDelay > frame){
frame++;
// Debug.Log("Yield a frame in LockCursor at " + Time.timeSinceLevelLoad);
yield return 0;
}
Screen.lockCursor = newState;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment