Get screen position of UI Toolkit element
Valid for:
Unity 2023.2.20f1 (tested), 2022.3com.unity.ui@2.0.0 - UI Toolkit
Use RuntimePanelUtils.CameraTransformWorldToPanel to convert the element's world position to panel coordinates, then set the element's translate style property.
var panelLocalPosition = RuntimePanelUtils.CameraTransformWorldToPanel(
element.panel, worldPosition, Camera.main);
element.style.translate = new StyleTranslate(
new Translate(panelLocalPosition.x, panelLocalPosition.y, 0));
Additional Information
Moving the element turned out to be tricky, but StyleTranslate worked best in the end.
Links to Discussions
- Get real screen position for a canvas UI element
- UI Toolkit Positioning Elements Documentation
- RuntimePanelUtils API Documentation
Conclusion
Getting the screen position of a UI Toolkit element requires converting between the world space position and the panel's local coordinate system. The RuntimePanelUtils class provides methods to handle this conversion.The code above allows you to move an UI Element on top of a gameobject (e.g. for RTS like games, name tags, health bars or HUD Elements).
Common issues that arise are accidentally using RectTransforms instead of VisualElements, or assuming the position is in screen space coordinates.
When working with UI Toolkit, always consider what coordinate space you are in and use the appropriate conversion methods as needed to translate between world, panel, and screen spaces.