Picking not working as expected

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:

Then I want to know which UI element is under the mouse so I’m using this code:

IPanel panel = mainUIDocument.rootVisualElement.panel;
Vector2 panelMousePos = RuntimePanelUtils.ScreenToPanel(panel, Input.mousePosition);
VisualElement visualElement = panel.Pick(panelMousePos);
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.

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:

IPanel panel = mainUIDocument.rootVisualElement.panel;
Vector2 screenMousePos = Input.mousePosition;
screenMousePos.y = Screen.height - screenMousePos.y;
Vector2 panelMousePos = RuntimePanelUtils.ScreenToPanel(panel, screenMousePos);
VisualElement visualElement = panel.Pick(panelMousePos);
return visualElement != null;

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 :slight_smile: