Skip to content

Instantly share code, notes, and snippets.

@dev-fredericfox
Last active January 28, 2023 22:57
Show Gist options
  • Save dev-fredericfox/c233a3d5f1dec5ac31b2dffe15da51a2 to your computer and use it in GitHub Desktop.
Save dev-fredericfox/c233a3d5f1dec5ac31b2dffe15da51a2 to your computer and use it in GitHub Desktop.
Unity: Positioning a UI Toolkit VisualElement relative to a GameObject
// the gameObject.transform.position for example, in my case a empty gameObject positioned over the character
Vector2 gameObjectToScreenPosition = Camera.main.WorldToScreenPoint(position);
Vector2 screenToUIToolkitPosition = RuntimePanelUtils.ScreenToPanel(_root.panel, gameObjectToScreenPosition);
Label combatText = new Label(text);
// set the label's text
combatText.text = text;
// set the label's color
combatText.style.color = color;
// Absolute
combatText.style.position = Position.Absolute;
// combatText the label's position
combatText.style.left = screenToUIToolkitPosition.x;
combatText.style.bottom = screenToUIToolkitPosition.y;
// add the label to the root
_root.Add(combatText);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment