Created
November 6, 2024 22:56
-
-
Save andydbc/d65a57cb6ecda84b24d4b64b4cde638b to your computer and use it in GitHub Desktop.
A simple utility for displaying object names in the Editor View. It can be used to draw custom labels, object names, or names of referenced objects.
This file contains 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
#if UNITY_EDITOR | |
using UnityEditor; | |
#endif | |
using UnityEngine; | |
public enum LabelMode | |
{ | |
GameObjectName = 0, | |
ReferenceName = 1, | |
Custom = 2 | |
} | |
public class DrawLabel : MonoBehaviour | |
{ | |
public LabelMode labelMode = LabelMode.GameObjectName; | |
public string label; | |
public Transform reference; | |
public Color color = Color.red; | |
public bool show = true; | |
public Vector3 offset = Vector3.zero; | |
private bool IsGameObjectMode => labelMode == LabelMode.GameObjectName; | |
private bool IsCustomMode => labelMode == LabelMode.Custom; | |
private bool IsReferenceMode => labelMode == LabelMode.ReferenceName; | |
private GUIStyle style = new GUIStyle(); | |
private string GetStringContent() | |
{ | |
switch(labelMode) | |
{ | |
case LabelMode.GameObjectName: | |
return gameObject.name; | |
case LabelMode.ReferenceName: | |
return reference == null ? "<Null>" : reference.name; | |
case LabelMode.Custom: | |
return label; | |
} | |
return string.Empty; | |
} | |
private void FollowReference() | |
{ | |
if (IsReferenceMode && reference != null) | |
transform.position = reference.transform.position; | |
} | |
private void Update() | |
{ | |
FollowReference(); | |
} | |
void OnDrawGizmos() | |
{ | |
#if UNITY_EDITOR | |
if (show) | |
{ | |
style.normal.textColor = color; | |
style.alignment = TextAnchor.MiddleCenter; | |
Handles.Label(transform.position + offset, GetStringContent(), style); | |
} | |
#endif | |
} | |
void OnValidate() | |
{ | |
if(IsGameObjectMode) | |
label = gameObject.name; | |
else if(IsReferenceMode && reference != null) | |
{ | |
label = reference.name; | |
FollowReference(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment