うにてぃブログ

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

【Unity】Null の場合 警告を出す Attribute

オブジェクト等の参照が無い場合、警告を出す Attribute を作成してみました

シリアライズされているフィールドに NotNull をつけると表示されるようになります

public class SampleMonoBehaviour : MonoBehaviour
{
    [SerializeField, NotNull]
    private RectTransform _root1;
    [SerializeField, NotNull]
    private int _value;
    [SerializeField, NotNull]
    private string _strValue;
}

f:id:hacchi_man:20201208005953p:plain

コード

using System;
using UnityEditor;
using UnityEngine;
 
[AttributeUsage(AttributeTargets.Field)]
public class NotNullAttribute : PropertyAttribute
{
}
 
[CustomPropertyDrawer(typeof(NotNullAttribute))]
public class NotNullDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        position.height = base.GetPropertyHeight(property, label);
        EditorGUI.PropertyField(position, property, label);
        position.y += position.height;
        if (IsRequire(property))
        {
            EditorGUI.HelpBox(position, "Set Value", MessageType.Error);
        }
    }
 
    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        if (IsRequire(property))
        {
            return base.GetPropertyHeight(property, label) * 2f;
        }
        return base.GetPropertyHeight(property, label);
    }
 
    private bool IsRequire(SerializedProperty property)
    {
        if (property.isArray)
            return property.arraySize == 0;
 
        switch (property.propertyType)
        {
            case SerializedPropertyType.Integer:
                return property.intValue == 0;

            case SerializedPropertyType.Float:
                return property.floatValue == 0f;

            case SerializedPropertyType.String:
                return property.stringValue == "";

            case SerializedPropertyType.ObjectReference:
                return property.objectReferenceValue == null;
        }
 
        return false;
    }
}