Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

Question Picking not working as expected

Discussion in 'UI Toolkit' started by BrianAmihan, May 17, 2022.

  1. BrianAmihan

    BrianAmihan

    Joined:
    Mar 10, 2022
    Posts:
    15
    Unity_X9kbJykULF.png

    Here is my setup. I have a container that has Picking Mode set to Ignore. Then two buttons have Picking Mode set to Position (strange mode name).

    Here is my hierarchy:
    Unity_M7mVwDKno9.png

    Then I want to know which UI element is under the mouse so I'm using this code:
    Code (CSharp):
    1. IPanel panel = mainUIDocument.rootVisualElement.panel;
    2. Vector2 panelMousePos = RuntimePanelUtils.ScreenToPanel(panel, Input.mousePosition);
    3. VisualElement visualElement = panel.Pick(panelMousePos);
    4. return visualElement != null;
    What I expect is that visualElement != null when the mouse is over one of the 2 buttons but it should be null when over any other part of the screen.

    What is happening is that it is always null when the container Picking Mode is set to Ignore and it is never null when the container Picking Mode is set to Position.

    Any tips? We need a way to determine which UI element is under the pointer.

    Thanks!

    Unity 2021.3.2f1, I'm not sure what version of UI Toolkit I'm using. It was included in the installation and I don't see an entry in the package manager.
     
  2. uBenoitA

    uBenoitA

    Unity Technologies

    Joined:
    Apr 15, 2020
    Posts:
    224
    Hi Brian,

    Input.mousePosition uses coordinates with bottom-left as the origin. UI Toolkit wants top-left origin screen coordinates. You need to pass in a flipped y coordinate. Try this one:

    Code (CSharp):
    1. IPanel panel = mainUIDocument.rootVisualElement.panel;
    2. Vector2 screenMousePos = Input.mousePosition;
    3. screenMousePos.y = Screen.height - screenMousePos.y;
    4. Vector2 panelMousePos = RuntimePanelUtils.ScreenToPanel(panel, screenMousePos);
    5. VisualElement visualElement = panel.Pick(panelMousePos);
    6. return visualElement != null;
     
  3. BrianAmihan

    BrianAmihan

    Joined:
    Mar 10, 2022
    Posts:
    15
    Ah! That makes sense! I just tested and this does indeed work.

    Thank you, I appreciate the help and I hope this thread helps others in the future :)