- Home /
Method of determining if a field is serialized?
I'm doing a bit of custom serialization using ISerializationCallbackReceiver
and then using reflection to serialize interfaces, generics etc. This is all working fine, but currently every applicable field is serialized, meaning the types that Unity does support are being serialized twice.
I really want to avoid this, but I haven't been able to find a simple method of telling if a given FieldInfo
will serialize or not. I'm halfway through writing an extension method to do this, but I don't want to be patching it and so on if at all possible.
Is there a simple way (or a community script) for telling if a given field will be serialized or not?
This is my current approach - unfinished, not tested or optimised - the "native" types are certainly not a complete list for example.
public static class FieldInfoExtensions
{
public static bool IsUnitySerialized(this FieldInfo fieldInfo)
{
object[] customAttributes = fieldInfo.GetCustomAttributes(true);
if (customAttributes.Any(x => x is NonSerializedAttribute))
{
return false;
}
if (fieldInfo.IsPrivate && !customAttributes.Any(x => x is SerializeField))
{
return false;
}
return fieldInfo.FieldType.IsUnitySerialized();
}
public static bool IsUnitySerialized(this Type type)
{
if (type.IsGenericType)
{
if (type.GetGenericTypeDefinition() == typeof(List<>))
{
return type.GetGenericArguments()[0].IsUnitySerialized();
}
return false;
}
if (type.IsEnum)
{
return true;
}
if (type.IsValueType)
{
return true;
}
Type typeUnityObject = typeof(UnityEngine.Object);
if (type.IsAssignableFrom(typeUnityObject))
{
return true;
}
Type[] typesNative =
{
typeof(bool),
typeof(byte),
typeof(float),
typeof(int),
typeof(string)
};
if (typesNative.Contains(type) || (type.IsArray && typesNative.Contains(type.GetElementType())))
{
return true;
}
return false;
}
}
Your answer
Follow this Question
Related Questions
Make the same serialized class as a ScriptableObject? 1 Answer
usage of FieldInfo.SetValue with SerializeField 2 Answers
Getting any type in Unity Inspector 1 Answer
Dictionary serialization woes 2 Answers
Public fields not showing in inspector 2 Answers