Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save paraself/c3fe55f333397319444dfd9cc48491a8 to your computer and use it in GitHub Desktop.
Save paraself/c3fe55f333397319444dfd9cc48491a8 to your computer and use it in GitHub Desktop.
Call from OnDrawGizmos() to draw text at Unity3D glocal position in Editor
public static void DrawString(Camera cam,string text, Vector3 worldPos, Color? colour = null)
{
if (IsValidCamera (cam) == false)
return;
UnityEditor.Handles.BeginGUI();
Color c = GUI.color;
if (colour.HasValue) GUI.color = colour.Value;
var view = UnityEditor.SceneView.currentDrawingSceneView;
if (view==null) return;
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 = c;
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 = c;
UnityEditor.Handles.EndGUI();
}
static bool IsValidCamera( Camera cam) {
if (Camera.current == null) return false;
if (Camera.current == cam) return true;
#if UNITY_EDITOR
if (SceneView.lastActiveSceneView != null && SceneView.lastActiveSceneView.camera != null && Camera.current == SceneView.lastActiveSceneView.camera) return true;
#endif
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment