Jarek Jarek - 3 months ago 19
C# Question

Unity: Issue with serialization since version 5.0 (Parent/Children relationship)

when I was using older versions of Unity there was no problem, but since uppgrade I keep receiving errors on all classes where class contains children of its type: Serialization depth limit exceeded at 'Formation'. There may be an object composition cycle in one or more of your serialized classes.

I have a class like this:

[Serializable]
public class Formation {
public List<Formation> Formations;
}


It writes about some cycles, but why there would be any problem when there is no infinite cycle, because every child instance must be initialized, so if user wants to make infinite cycle he would do it, but only by initializing children explicitly...

Is this some bug? I read already some thread on forum suggesting removing children, but I don't get why this behavior even occurs.

Btw on this class I wrote last time I didn't even serialize, and didn't even make list instance

Answer

I had similar issue of cyclic serialization. I solved it by explicitly making the parent instance nonserializable.

e.g.

[Serializable]
class A
{
    [SerializeField]
    B _bInstance;
    ...
}
...
[Serializable]
class B
{
    A _aInstance;
    ...
}

becomes

[Serializable]
class A
{
    [SerializeField]
    B _bInstance;
    ...
}
...
[Serializable]
class B
{
    [NonSerialized]
    A _aInstance;
    ...
}

Hope this will help.