I am currently working on a project there i was in need of tool tips. If you worked with UiToolkit before you know there are tool tips for the editor environment but not yet for the runtime environment.
But luckily its very easy to get the tool tips into the runtime environment. We just have to write a new manipulator and add it to the elements who needs tool tips.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class ToolTipManipulator : Manipulator
{
private VisualElement element;
public ToolTipManipulator()
{
}
protected override void RegisterCallbacksOnTarget()
{
target.RegisterCallback<MouseEnterEvent>(MouseIn);
target.RegisterCallback<MouseOutEvent>(MouseOut);
}
protected override void UnregisterCallbacksFromTarget()
{
target.UnregisterCallback<MouseEnterEvent>(MouseIn);
target.UnregisterCallback<MouseOutEvent>(MouseOut);
}
private void MouseIn(MouseEnterEvent e)
{
if (element == null)
{
element = new VisualElement();
element.style.backgroundColor = Color.blue;
element.style.position = Position.Absolute;
element.style.left = this.target.worldBound.center.x;
element.style.top = this.target.worldBound.yMin;
var label = new Label(this.target.tooltip);
label.style.color = Color.white;
element.Add(label);
var root = (VisualElement)UiHelper.FindRootElement(this.target);
root.Add(element);
}
element.style.visibility = Visibility.Visible;
element.BringToFront();
}
private void MouseOut(MouseOutEvent e)
{
element.style.visibility = Visibility.Hidden;
}
}
Just copy this code into ToolTipManipulator.cs in your Unity project and following code to things who need to have a tool tip.
//Optional if icons tooltip was not set before in UiBuilder ...
element.Q<VisualElement>("Icon").tooltip = "I am a tooltip";
element.Q<VisualElement>("Icon").AddManipulator(new ToolTipManipulator());
All done!