Search Unity

If statement - logic problem

Discussion in 'Scripting' started by Denisowator, Mar 10, 2019.

  1. Denisowator

    Denisowator

    Joined:
    Apr 22, 2014
    Posts:
    918
    I want to call a method whenever I'm holding down RMB, and as long as I'm not hovering over UI.
    But I also want it so that if I'm holding down RMB and I drag the mouse off the UI, the method doesn't get called. This is what I'm struggling to do.

    This is how I'm checking for the UI:
    Code (CSharp):
    1. hoveringOverUI = EventSystem.current.IsPointerOverGameObject();
    And this is the code that calls the method:
    Code (CSharp):
    1. if (Input.GetMouseButton(1) && hoveringOverUI == false) {
    2.    // Call method
    3. }
    I'm pretty sure a custom bool for checking RMB would be involved, but every solution I thought of, either ended up being the original, or somehow causing other issues (like never being able to call the method).
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    You could just add a bool to check if it was pressed when not over the UI.

    Code (CSharp):
    1.         private bool _rmbPressedOffUI;
    2.  
    3.         if (Input.GetMouseButtonUp(1))
    4.             _rmbPressedOffUI = false;
    5.  
    6.         if (hoveringOverUI)
    7.             return;
    8.  
    9.         if (Input.GetMouseButtonDown(1))
    10.             _rmbPressedOffUI = true;
    11.  
    12.         if(Input.GetMouseButtonDown(1) && !_rmbPressedOffUI)
    13.         {
    14.             //Call Method
    15.         }
     
    Denisowator likes this.
  3. Denisowator

    Denisowator

    Joined:
    Apr 22, 2014
    Posts:
    918
    Doesn't seem to be executing the last check because of "!_rmbPressedOffUI". If I change it to "_rmbPressedOffUI == true" it goes back to acting as it did originally (obviously).

    Tried to change the whole code in a lot of ways, always ends up acting like the original.
     
    Last edited: Mar 10, 2019
  4. Denisowator

    Denisowator

    Joined:
    Apr 22, 2014
    Posts:
    918
    Got it working. Just needed to set the second bool when RMB was pressed, then check against it at the start (before the if check calling return).

    Thank you for the help. :)
    Code (CSharp):
    1. if (_rmbPressedOffUI == true) // Call method
    2.  
    3. if (Input.GetMouseButtonUp(1)) _rmbPressedOffUI = false;
    4.  
    5. if (hoveringOverUI) return;    // If hovering over UI, stop rest of method code from running
    6.  
    7. if(Input.GetMouseButtonDown(1)) _rmbPressedOffUI = true;    // When pressing RMB, set bool to true
     
    Last edited: Mar 10, 2019