うにてぃブログ

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

【Unity】SerializedProperty と System.Type の Array と List の判定と Type 取得

Array と List の判定

SerializedProperty のみでは Array か List どちらか知ることができますが、System.Typeを利用しないとどちらかを判定できません

string も内部的には char の Array なので string のチェックをする必要があります

    public static bool IsArrayOrList(this SerializedProperty prop)
    {
        return property.isArray && property.propertyType != SerializedPropertyType.String;
    }
  
    public static bool IsArrayOrList(this System.Type type)
    {
        return this.IsArray(type) || this.IsList(type);
    }
 
    public static bool IsArray(this System.Type type)
    {
        return type.IsArray;
    }
 
    public static bool IsList(this System.Type type)
    {
        return type.IsGenericType && (object) type.GetGenericTypeDefinition() == (object) typeof (List<>);
    }

Array と List の Type 取得

SerializedProperty では string でしか Type を取得できないので、Typeに変換する必要があります

System.Type では Array と List 時で取得方法が異なります

    public static string GetArrayOrListType(this SerializedProperty prop)
    {
        return property.arrayElementType;
    }
 
    public static Type GetArrayType(this System.Type type)
    {
        return type.GetElementType()
    }
 
    public static Type GetListType(this System.Type type)
    {
        return type.GetGenericArguments()[0];
    }