うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】Asset のパスを表示する CustomAttirbute

f:id:hacchi_man:20200801202030p:plain

using UnityEngine;
 
public class PathAttribute : PropertyAttribute
{
}
using UnityEditor; 
 
[CustomPropertyDrawer(typeof(PathAttribute))]
public class PathAttributeDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        position.height = EditorGUIUtility.singleLineHeight;
        EditorGUI.PropertyField(position, property, label);
        var path = GetPath(property);
 
        if (string.IsNullOrEmpty(path))
            return;
 
        position.y += position.height;
        EditorGUI.LabelField(position, path, EditorStyles.helpBox);
    }
 
    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        var size = string.IsNullOrEmpty(GetPath(property)) ? 1 : 2;
        return EditorGUIUtility.singleLineHeight * size;
    }
 
    private string GetPath(SerializedProperty property)
    {
        if (property.objectReferenceValue == null)
            return string.Empty;
 
        return AssetDatabase.GetAssetPath(property.objectReferenceValue);
    }
}