Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Forked from yasirkula/CommentComponent.cs
Created November 4, 2024 21:03
Show Gist options
  • Save unitycoder/595d72dbd495b87ff01726f5a90240b9 to your computer and use it in GitHub Desktop.
Save unitycoder/595d72dbd495b87ff01726f5a90240b9 to your computer and use it in GitHub Desktop.
Adding comments to Inspector via a component in Unity
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
[AddComponentMenu("Comment")]
public class CommentComponent : MonoBehaviour
{
#if UNITY_EDITOR
[SerializeField]
private string comment;
[CustomEditor(typeof(CommentComponent))]
[CanEditMultipleObjects]
public class CommentComponentEditor : Editor
{
private SerializedProperty commentProp;
private GUIStyle commentStyle;
private float inspectorWidth;
protected void OnEnable()
{
commentProp = serializedObject.FindProperty("comment");
}
public override void OnInspectorGUI()
{
if (commentStyle == null)
{
commentStyle = new GUIStyle(EditorStyles.wordWrappedLabel);
commentStyle.normal.textColor = commentStyle.focused.textColor = commentStyle.hover.textColor = Color.green;
}
serializedObject.Update();
Rect rect = EditorGUILayout.GetControlRect(false, commentStyle.CalcHeight(new GUIContent(commentProp.stringValue), inspectorWidth));
if (Event.current.type == EventType.Repaint)
inspectorWidth = rect.width;
EditorGUI.DrawRect(rect, Color.black); // Draw dark background
EditorGUI.BeginProperty(rect, GUIContent.none, commentProp);
EditorGUI.BeginChangeCheck();
string newComment = EditorGUI.TextArea(rect, commentProp.stringValue, commentStyle);
if (EditorGUI.EndChangeCheck())
commentProp.stringValue = newComment;
EditorGUI.EndProperty();
serializedObject.ApplyModifiedProperties();
}
}
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment