[UITK] Finding Child VisualElement World Space Position
Solution
Unity 2021.3.x - Unity 6.3.x
Published 30 days ago
When utilizing a UIDocument in world space, retrieving the 3D scene coordinates of a nested VisualElement is non-trivial. The standard worldBound property returns coordinates relative to the panel origin rather than the 3D scene, leading to incorrect positioning when attempting to align game objects or effects with specific UI elements.
Calculating the 3D position requires bridging the gap between the UITK panel coordinate system and the Unity world space. 1. Access the target VisualElement and retrieve its worldBound property to get the element’s layout rect relative to the panel. 2. Calculate the center of the worldBound to identify the 2D point of interest. 3. Transform this 2D point into a Vector3. Since UITK panel space is typically Y-down, you must account for the local orientation of your world-space Canvas or quad. 4. Use transform.TransformPoint on the GameObject containing the UIDocument to convert the panel-relative point into scene coordinates. This effectively treats the UI panel as a local plane within your scene’s 3D space.
Additional Tips
- The worldBound property is only calculated during the layout pass; ensure your calculation logic runs after a
GeometryChangedEventif the UI is dynamic. - Ensure the
PanelSettingsasset is set toWorldrender mode for the calculation to be relevant to 3D space. - If your UI has significant depth or scaling, use the
worldTransformmatrix of theVisualElementto multiply your local position before applying the scene transformation.
TL;DR
To obtain the 3D world space position of a child VisualElement, you must map its panel-space worldBound center to the world-space Transform of the host GameObject using coordinate transformation matrices.
Related Posts Haven't quite found a solution to your problem? We think these posts might help you.
Content inspired by a Unity discussion post.