うにてぃブログ

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

【Unity】【CustomPropertyDrawer】Inspector に Preview を表示する

PropertyAttribute を作成して Inspector で アセットの Preview を表示できるように拡張する

Editor.DrawPreview を呼び出せば Preview が表示できるようになります

しかしながら、高さに関しては適当にしてるので利用する際は適切に処理を変えてください

using UnityEditor;
using UnityEngine;
 
public class PreviewAttribute : PropertyAttribute
{
}
 
[CustomPropertyDrawer(typeof(PreviewAttribute))]
public class DisplayDrawer : PropertyDrawer
{
    private Editor _cacheEditor;
    private const int PreviewMin = 150;
 
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        if (property.propertyType != SerializedPropertyType.ObjectReference || property.objectReferenceValue == null)
        {
            EditorGUI.PropertyField(position, property, label);
            return;
        }
 
        position.height = base.GetPropertyHeight(property, label);
        EditorGUI.PropertyField(position, property, label);
        property.isExpanded = EditorGUI.Foldout(position, property.isExpanded, GUIContent.none);
        if (!property.isExpanded)
            return;

        var height = Mathf.Min(PreviewMin, EditorGUIUtility.currentViewWidth);

        position.y += position.height;
        position.height = height;
        if (_cacheEditor == null)
            _cacheEditor = Editor.CreateEditor(property.objectReferenceValue);
        
        _cacheEditor.DrawPreview(position);
    }
 
    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        if (!property.isExpanded)
            return base.GetPropertyHeight(property, label);
         
        if (property.propertyType != SerializedPropertyType.ObjectReference || property.objectReferenceValue == null)
            return base.GetPropertyHeight(property, label);
 
        var height = Mathf.Min(PreviewMin, EditorGUIUtility.currentViewWidth);
        return base.GetPropertyHeight(property, label) + height;
    }
}

サンプル

uGUI の Prefab は Preview が表示できなかったので、気が向いたら対応できるようにしようかなと思います

f:id:hacchi_man:20200305003458p:plain:h500

using UnityEditor;
using UnityEngine;

public class SampleMonoBehaviour : MonoBehaviour
{
    [SerializeField]
    [Preview]
    private GameObject _preview;

    [SerializeField]
    [Preview]
    private Sprite _sprite;
}