Search Unity

Question Menus & cursor - how to sync cursor state with opened panel(s)?

Discussion in 'Scripting' started by LambdaTheDev, Apr 21, 2021.

  1. LambdaTheDev

    LambdaTheDev

    Joined:
    Jan 15, 2020
    Posts:
    57
    Hello guys, let me quickly explain you my situation:

    I have some panels, for example - inventory, admin panel, esc menu etc...

    But, when panel is active, cursor should be unlocked, otherwise - locked.

    My first solution was to code something like this:

    Code (CSharp):
    1. Update():
    2. - If pressed ESC
    3. - if esc menu opened:
    4.    - hide esc menu
    5.    - lock cursor
    6. - else:
    7.    - show esc menu
    8.    - unlock cursor
    But, what if I have more panels opened at once? Cursor state may be overwritten by previous state.

    Does anybody have an idea how to setup tabs system (one panel at once visible solution is possible), so cursors are always correct?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,752
    You could increment a counter when you open a panel, then decrement it when you close it.

    After incrementing it, if it is 1, unlock the cursor

    After decrementing it, if it is 0, re-lock the cursor

    Personally, I'm always loathe to let the Cursor class do anything, as it may have weird edge cases when the app loses/regains focus. I also see a lot of people in here from time to time reporting issues with it. You might want to make your own cursor, hide the system cursor and just use its input to drive your cursor.