Skip to content

Instantly share code, notes, and snippets.

@thebne
Last active May 2, 2022 15:14
Show Gist options
  • Save thebne/838de2cf8033db15353dffe1256790fa to your computer and use it in GitHub Desktop.
Save thebne/838de2cf8033db15353dffe1256790fa to your computer and use it in GitHub Desktop.
Find recursive references for Serializables to eliminate "Serialization depth limit 10 exceeded ... There may be an object composition cycle in one or more of your serialized classes." warning in Unity
// this helped me trace & eliminate a bug with this warning:
// Serialization depth limit 10 exceeded at '<Type>.<Field>'. There may be an object composition cycle in one or more of your serialized classes.
public static IEnumerable<FieldInfo> GetRecursiveReferences<T>()
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (var type in assembly.GetTypes())
{
if (!type.IsDefined(typeof(System.SerializableAttribute), true))
continue;
foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
if (field.IsDefined(typeof(NonSerializedAttribute), false))
continue;
if (field.FieldType == typeof(T))
yield return field;
else if (field.FieldType.IsGenericType && field.FieldType.GetGenericTypeDefinition() ==
typeof(System.Collections.Generic.List<>))
{
if (typeof(T).IsAssignableFrom(field.FieldType.GenericTypeArguments[0]))
yield return field;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment