Created
August 2, 2018 13:34
-
-
Save jeffvella/fc7e66dd3f871785bb6ebb6d98ca1b2f to your computer and use it in GitHub Desktop.
Drawing Debug text with background in Unity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void DrawString(string text, Vector3 worldPos, Color? textColor = null, Color? backColor = null) | |
{ | |
UnityEditor.Handles.BeginGUI(); | |
var restoreTextColor = GUI.color; | |
var restoreBackColor = GUI.backgroundColor; | |
GUI.color = textColor ?? Color.white; | |
GUI.backgroundColor = backColor ?? Color.black; | |
var view = UnityEditor.SceneView.currentDrawingSceneView; | |
if (view != null && view.camera != null) | |
{ | |
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 = restoreTextColor; | |
UnityEditor.Handles.EndGUI(); | |
return; | |
} | |
Vector2 size = GUI.skin.label.CalcSize(new GUIContent(text)); | |
var r = new Rect(screenPos.x - (size.x / 2), -screenPos.y + view.position.height + 4, size.x, size.y); | |
GUI.Box(r, text, EditorStyles.numberField); | |
GUI.Label(r, text); | |
GUI.color = restoreTextColor; | |
GUI.backgroundColor = restoreBackColor; | |
} | |
UnityEditor.Handles.EndGUI(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment