Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Private field in class serialized with JsonUtility.ToJson(...) causes depth limit error.

Discussion in 'Scripting' started by MechaWolf99, Feb 20, 2020.

  1. MechaWolf99

    MechaWolf99

    Joined:
    Aug 22, 2017
    Posts:
    293
    I have a class with a private field that is of the parent class type which also contains a public field of the child class type. Private fields are not serialized, so this should not be an problem.
    But using JsonUtility.ToJson with it causes unity to give the Serialization depth limit 7 exceeded warning.
    I have no idea why. Marking it with [NonSerialized] stops it. But I shouldn't need to any way.

    Example:
    Code (CSharp):
    1. [Serializable]
    2. public class Apple
    3. {
    4.     private Tree _parentTree; // Causes Error
    5. }
    6.  
    7. [Serializable]
    8. public class Tree
    9. {
    10.     public Apple grownApple;
    11. }
    Serializing an instance of Apple, or Tree with ToJson causes the warning.
     
  2. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    I'm not sure why your private field is serialized by default, but you cannot "circularly serialize," meaning you can't serialize a class that has a serialized field that itself has a serialized reference to the first class. Trying to do so creates an endless chain of references (Tree has an Apple, which has a Tree, which has an Apple, which has a Tree... ). Each reference deep is another layer of "Serialization depth." If they didn't give up and give you that error, you would get stuck in an infinite loop and Unity would crash.

    // This works
    [Serializable] public class A { }
    [Serializable] public class B { public A field; }

    // This does not work
    [Serializable] public class A { public B field; }
    [Serializable] public class B { public A field; }
     
  3. MechaWolf99

    MechaWolf99

    Joined:
    Aug 22, 2017
    Posts:
    293
    It doesn't actually serialize the private field. But throws the warning for it. I wasn't trying to serialize it, because like you said that would create a loop.