【Unity】 自作Attributeでコメント表示
練習としてパラメータにマウスオーバーしたら
コメント表示用Attributeを作成してみます
CommentAttribute
PropertyAttributeを継承して、コメント保存用クラスを作成します
// CommentAttribute.cs using UnityEngine; public class CommentAttribute : PropertyAttribute { public string Comment {get; private set;} public CommentAttribute(string comment) { Comment = comment; } }
CommentDrawer
GUIの描画処理、
受け取ったGUIContentにtooltipを設定して描画します
// CommentDrawer.cs (Assets/Editor内に置く) using UnityEngine; using UnityEditor; [CustomPropertyDrawer(typeof(CommentAttribute))] public class CommentDrawer : PropertyDrawer { public override void OnGUI(Rect position,SerializedProperty property,GUIContent label) { CommentAttribute commentAttribute = (CommentAttribute)attribute; GUIContent content = new GUIContent(label); content.tooltip = commentAttribute.Comment; this.DrawDefaultProperty(position,property,content); // 後で説明 } }
※注意!! label.tooltip = commentAttribute.Comment; 直接設定したら、それ以降のプロパティに影響してしまいます
DrawDefaultProperty
PropertyDrawerのデフォルト描画は用意されていませんでしたので
拡張メソッドを使って作成します
using UnityEngine; using UnityEditor; public static class PropertyDrawerExtension { public static void DrawDefaultProperty(this PropertyDrawer propertyDrawer,Rect position, SerializedProperty property, GUIContent label) { if(property.propertyType == SerializedPropertyType.Boolean) { property.boolValue = EditorGUI.Toggle(position,label,property.boolValue); } if(property.propertyType == SerializedPropertyType.Integer) { property.intValue = EditorGUI.IntField(position,label,property.intValue); } if(property.propertyType == SerializedPropertyType.Float) { property.floatValue = EditorGUI.FloatField(position,label,property.floatValue); } } }
ひたすらタイプごとの表示を書きます
使用方法
// CommentSample.cs public class CommentSample : MonoBehaviour { [Comment("コメントサンプル")] public int val; }
Inspectorのパラメータ(val)にマウスオーバーした状態