Search Unity

Locking the mouse

Discussion in 'Scripting' started by Rastafari, Nov 11, 2013.

  1. Rastafari

    Rastafari

    Joined:
    Jul 18, 2011
    Posts:
    196
    Im attempting to script something that locks the mouse when pressing A.
    Now it just jumps back to the center of the screen.


    Code (csharp):
    1. var locked = true;
    2.  
    3.  function Update(){
    4.      if(Input.GetKeyDown(KeyCode.A)){
    5.         if(locked == false){
    6.         Screen.lockCursor = true;
    7.         locked = true;
    8.         }
    9.         if(locked == true){
    10.         Screen.lockCursor = false;
    11.         locked = false;
    12.         }
    13.     }
    14. }
    15.  
     
  2. Fluzing

    Fluzing

    Joined:
    Apr 5, 2013
    Posts:
    815
    Your code is incorrect. You should add an else statement.

    Code (csharp):
    1. if(Input.GetKeyUp(KeyCode.A))
    2. {
    3.        Screen.lockCursor = !Screen.lockCursor
    4. }
    In the code you have now, it will get unlocked right away.

    Edit:
    You don't even need the locked Boolean.

    Edit edit:
    You don't even need the IF-statement.

    Last edit:
    It is better to use GetKeyUp to prevent pressing it multiple times.
     
    Last edited: Nov 11, 2013