Getting rid of 'Serialization Depth Limit Exceeded' error messages

I have a class in my game called ‘Goal’ that stores my characters’ individual goals. Each of these goals can have subgoals of type ‘Goal’, and each of these subgoals can have subgoals, and so on. I never actually reach a depth of more than 3 or 4. The class includes a ‘[System.Serializable]’ for debugging purposes. However, I’m getting a bunch of errors stating:

“Serialization depth limit exceeded at ‘Goal’. There may be an object composition cycle in one or more of your serialized classes.”

This only started happening when I updated to Unity 4.6.2f1. Any fixes/workarounds for something like this?

If you declare your sub goals as an array of Goal your class is able to actually don’t have any subgoal. That would be the preferred way of declaring subgoals.

If you need them to be single member variables, you can’t “get rid” of those errors. Your structure actually builds an infinite structure. The depth limitation is just a security trap to avoid a system crash caused by the serialization system.

So either don’t mark it as Serializable or don’t build an infinite structure.

@Bunny83, basically this problem can be solved by storing all your objects that can have children of the same type in a Container that will handle children-parents relationships on serialization; In your case you just need to create a class that will store all your goals.
Here is an example:

using System;
using System.Runtime.Serialization;
using System.Collections.Generic;

[Serializable]
public class MyObject
{
    [NonSerializeble]
    public MyObject child;
}

//this is the class that you are going to serialize
[Serializable]
public class ObjectsContrainer
{
    private List<MyObject> allObjects;
    private List<serializationInfo> serializationInfos;

    //save info about the children in a way that we dont get any cycles
    [OnSerializing]
    private void OnSerializingStarted(StreamingContext context)
    {
        serializationInfos = new List<serializationInfo>();
        foreach (var obj in allObjects)
        {
            serializationInfo info = new serializationInfo {
                parentIndex = allObjects.FindIndex(x => x == obj),
                childIndex =  allObjects.FindIndex(x => x == obj.child)
            serializationInfos.Add(info);
        }
    }

    //restore info about the children
    [OnDeserialized]
    private void OnDeserialized(object o)
    {
        //restore connections
        foreach (var info in serializationInfos)
        {
            var parent = allObjects[info.parentIndex];
            parent.child = allObjects[info.childIndex];
        }
    }
    
    [Serializable]
    private struct serializationInfo
    {
        public int childIndex;
        public int parentIndex;
    }
}