While watching Gizmos static helpers, I see it’s lacking of a method to display a text, that can be useuful
So I googled to find a solution and I find a snippet that I adapted to my needs, so I created an extension of Component, here the code (I used UnityEngine namespace so it should always be available)
namespace UnityEngine
{
public static class ComponentExtensions
{
static public void DrawGizmoString(this Component component, string text, Vector3 worldPos, Color? color = null)
{
var view = UnityEditor.SceneView.currentDrawingSceneView;
if (view == null) return;
UnityEditor.Handles.BeginGUI();
var previousColor = GUI.color;
if (color.HasValue) GUI.color = color.Value;
Vector3 screenPos = view.camera.WorldToScreenPoint(worldPos);
if (screenPos.y < 0 || screenPos.y > Screen.height || screenPos.x < 0 || screenPos.x > Screen.width || screenPos.z < 0)
{
GUI.color = previousColor;
UnityEditor.Handles.EndGUI();
return;
}
Vector2 size = GUI.skin.label.CalcSize(new GUIContent(text));
GUI.Label(new Rect(screenPos.x - (size.x / 2), -screenPos.y + view.position.height + 4, size.x, size.y), text);
GUI.color = previousColor;
UnityEditor.Handles.EndGUI();
}
}
}
and I used it to display Health points on every GameObject using Health component (not just for selected ones)
just add this to your Health component
private void OnDrawGizmos()
{
this.DrawGizmoString($"Health: {this.healthPoints}", this.transform.position, Color.black);
}
the result is something like this
(this extension could be generalized and e.g. we should update it to accept test positioning like center, left, right etc…)