UnityRef is currently in early development. Some features may be incomplete and/or not functioning.

UNITYREF

Your Pit Stop For Solving ANYTHING in Unity

ui

[UITK] Finding Child VisualElement World Space Position

Solution

ui toolkit

Unity 2021.3.x - Unity 6.3.x

Published 30 days ago

Issue

 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.

Explanation

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 GeometryChangedEvent if the UI is dynamic.
  • Ensure the PanelSettings asset is set to World render mode for the calculation to be relevant to 3D space.
  • If your UI has significant depth or scaling, use the worldTransform matrix of the VisualElement to 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.