うにてぃブログ

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

【Unity】下にスペースを追加する Attribute

通常 スペースを入れる場合

   [SerializeField]
    private Button buttonPlay;
    [SerializeField, Space]
    private Button buttonReverse;

上 にスペースが追加されます

f:id:hacchi_man:20210109010138p:plain:w350

が 下に スペースを追加したかったので EndSpaceAttribute を作成しました

   [SerializeField, UnderSpace]
    private Button buttonReverse;

これを利用すると Base クラス側の最後にスペースを追加できるのでちょっと分かりやすくできたりします

f:id:hacchi_man:20210109010450p:plain:w350

コード

using UnityEditor;
using UnityEngine;

[AttributeUsage(AttributeTargets.Field)]
public class UnderSpaceAttribute : PropertyAttribute
{
    public int Space;
    public EndSpaceAttribute(int space = 20)
    {
        Space = space;
    }
}
 
[CustomPropertyDrawer(typeof(UnderSpaceAttribute))]
public class UnderSpaceDrawer : PropertyDrawer
{
    private int? _space;
    private int space
    {
        get
        {
            _space ??= (attribute as EndSpaceAttribute).Space;
            return _space.Value;
        }
    }
    
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        position.height = base.GetPropertyHeight(property, label);
        EditorGUI.PropertyField(position, property, label);
    }
 
    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        return base.GetPropertyHeight(property, label) + space;
    }
}