Search Unity

Setting cursor to active/not active

Discussion in 'Scripting' started by ChuckieGreen, Nov 22, 2017.

  1. ChuckieGreen

    ChuckieGreen

    Joined:
    Sep 18, 2017
    Posts:
    358
    Hi, So when my game starts my cursor is set to locked. But I want it to be unlocked when I go into the inventory, so i set up this code
    Code (CSharp):
    1. void Update () {
    2.  
    3.         float translation = Input.GetAxis("Vertical") * speed;
    4.         float straffe = Input.GetAxis("Horizontal") * speed;
    5.         translation *= Time.deltaTime;
    6.         straffe *= Time.deltaTime;
    7.  
    8.         transform.Translate(straffe, 0, translation); // straffe = x, translate = z (back/forth)
    9.  
    10.         if (Input.GetKeyDown ("escape"))                        // Turn cursor back on.
    11.             Cursor.lockState = CursorLockMode.None;
    12.         else
    13.         if (Input.GetKeyDown("i") && InvActive == false)
    14.         {
    15.             InvActive = true;
    16.             Debug.Log("invActive");
    17.         }
    18.         else
    19.         if (InvActive == true)
    20.         {
    21.             Cursor.lockState = CursorLockMode.None;
    22.         }
    23.         else
    24.          if (Input.GetKeyDown("i") && InvActive == true)
    25.           {
    26.             InvActive = false;
    27.          }
    28.        else
    29.         if (InvActive == false)
    30.         {
    31.             Cursor.lockState = CursorLockMode.Locked;
    32.         }
    This partially works, when i press 'I' to bring the inventory up, it make the cursor unlocked so i can select items from the inventory, however, it does not seem to change back to locked when 'I' is pressed again to come out of the inventory.

    I am beginning to think all the if else statements is not the best way to handle this situation. If anyone can shed some light on either why it is not working this way, or perhaps a better way to handle this, it would be greatly appreciated
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Okay, your escape one is doing nothing, I think after all the logic executes..
    (You could add it back , if you use this code change, if you wanted to).
    Code (csharp):
    1.  
    2. if (Input.GetKeyDown("i")) {
    3.    InvActive = !InvActive;
    4.    Cursor.lockState = InvActive ? CursorLockMode.None : CursorLockMode.Locked;
    5.    }
    6.  
    You just want locked, not locked an invisible -- just checking? I think this should work.
    I also think your code, though longer, should have worked, too.