Search Unity

Mouse Lock State

Discussion in 'Scripting' started by Milambur88, Feb 14, 2020.

  1. Milambur88

    Milambur88

    Joined:
    Jan 15, 2020
    Posts:
    28
    I have a script for moving my player camera but in this script i lock the mouse, how would i go about changing this when a UI box appears?

    Code (CSharp):
    1. {
    2.  
    3.     public float mouseSensitivity = 100f;
    4.    
    5.     public Transform playerBody;
    6.  
    7.     float xRotation = 0f;
    8.  
    9.     // Start is called before the first frame update
    10.     void Start()
    11.     {
    12.         Cursor.lockState = CursorLockMode.Locked;
    13.     }
    14.  
    15.     // Update is called once per frame
    16.     void Update()
    17.     {
    18.         // this is telling unity to get the mouse x and y feedback.
    19.         float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
    20.         float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
    21.  
    22.         xRotation -= mouseY;
    23.         // this clamps the camera roatation so it cannot exceed this angle
    24.         xRotation = Mathf.Clamp(xRotation, -90f, 90f);
    25.  
    26.         transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
    27.  
    28.        
    29.         // this is the camera rotation
    30.         playerBody.Rotate(Vector3.up * mouseX);
    31.     }
    32. }
     
  2. Karrzun

    Karrzun

    Joined:
    Oct 26, 2017
    Posts:
    129
    The answer is as always: it depends. When you know for sure that after the UI box disappeared, you return to your gameplay, you can simply add a script to that UI box that contains the following methods:

    Code (CSharp):
    1. public class UnlockMouseForPopUps : MonoBehaviour
    2. {
    3.     void OnEnable ()
    4.     {
    5.         Cursor.lockState = CursorLockMode.Confined;
    6.     }
    7.  
    8.  
    9.     void OnDisable ()
    10.     {
    11.         Cursor.lockState = CursorLockMode.Locked;
    12.     }
    13. }
    If the user is able to open some sort of menu or anything from there, however, that won't cut it.
     
  3. Milambur88

    Milambur88

    Joined:
    Jan 15, 2020
    Posts:
    28
    Thanks this works sort of I can now see my mouse when the pop up is displayed but it remains locked to the centre of the screen.

    should i now reference the original screen lock and disable it maybe with an if statement?
     
  4. Milambur88

    Milambur88

    Joined:
    Jan 15, 2020
    Posts:
    28
    Okay never mind i got it.

    All i needed to do was change .Confined to .None and this freed my mouse movement.
    thanks for your help