Skip to content

Instantly share code, notes, and snippets.

@edwardrowe
Created April 28, 2021 18:26
Show Gist options
  • Save edwardrowe/6485239ebc19f1383589b4fdc48f2fd0 to your computer and use it in GitHub Desktop.
Save edwardrowe/6485239ebc19f1383589b4fdc48f2fd0 to your computer and use it in GitHub Desktop.
Unity CommentComponent
using System.Collections;
using UnityEngine;
/// <summary>
/// Simple component that allows users to write comments to place on MonoBehaviours. Mainly for testmaps.
/// </summary>
public class CommentComponent : MonoBehaviour
{
[TextArea(3, 10)]
[SerializeField]
[Tooltip("Enter comment text here")]
private string text;
/// <summary>
/// Gets or sets the body of the comment, mainly used for display of information on test maps.
/// </summary>
/// <value>The body.</value>
public string Text
{
get => this.text;
set => this.text = value;
}
}
using UnityEditor;
using UnityEngine;
using RedBlueGames.Tools;
/// <summary>
/// Draws a Comment Icon on GameObjects in the Hierarchy that contain the Comment component.
/// </summary>
[InitializeOnLoad]
public class CommentHierarchyIcon
{
private static readonly Texture2D Icon;
private static readonly Texture2D ParentIcon;
static CommentHierarchyIcon()
{
Icon = AssetDatabase.LoadAssetAtPath("Assets/Gizmos/CommentIcon.png", typeof(Texture2D)) as Texture2D;
ParentIcon = AssetDatabase.LoadAssetAtPath("Assets/Gizmos/CommentIcon_Parent.png", typeof(Texture2D)) as Texture2D;
if (Icon == null)
{
return;
}
EditorApplication.hierarchyWindowItemOnGUI += DrawIconOnWindowItem;
}
private static void DrawIconOnWindowItem(int instanceID, Rect rect)
{
if (Icon == null)
{
return;
}
GameObject gameObject = EditorUtility.InstanceIDToObject(instanceID) as GameObject;
if (gameObject == null)
{
return;
}
var comments = gameObject.GetComponentsInChildrenPooled<CommentComponent>();
foreach (var comment in comments)
{
if (!string.IsNullOrEmpty(comment.Text))
{
bool commentIsOnThisObject = comment.gameObject.Equals(gameObject);
if (commentIsOnThisObject)
{
DrawIcon(Icon, rect, comment.Text);
break;
}
else
{
if (ParentIcon != null)
{
// Could eventually use HierarchyProperty (and Find / IsExpanded) to only show this icon when collapsed)
DrawIcon(ParentIcon, rect, string.Empty);
break;
}
}
}
}
comments.Free();
}
private static void DrawIcon(Texture2D icon, Rect rect, string tooltip)
{
float iconWidth = 15;
EditorGUIUtility.SetIconSize(new Vector2(iconWidth, iconWidth));
var padding = new Vector2(20, 0);
var iconDrawRect = new Rect(rect.xMax - (iconWidth + padding.x), rect.yMin, rect.width, rect.height);
var iconGUIContent = new GUIContent(icon, tooltip);
EditorGUI.LabelField(iconDrawRect, iconGUIContent);
EditorGUIUtility.SetIconSize(Vector2.zero);
}
}
@edwardrowe
Copy link
Author

Note this has a few utility dependencies that are not imported.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment