serialization, list, circular reference issue

How can I enable serialization on a list of objects that reference the next object in the list (so that my list is full of objects that reference each other in a circular fashion)

I am trying to understand why the following does not work:

public class Test : MonoBehaviour
    public List<ConnectedObjects> test;

public class ConnectedObjects
    public ConnectedObjects nextObject;
    public int i = 0;

The connected points are intended to point to the next object in their list, and where the last one points back to the start of the list.

Unity does not seem to let me do this. I do not understand why. the public member ‘i’ is editable in the inspector when I populate ‘test’, but not ‘nextObject’. Also, if I populate the list with some code that runs in the editor, the list will never be saved - the references will get broken when I relaunch unity.

Strangely enough, I can have the following code:

public class Test : MonoBehaviour
    public Test nextTest;

where 2 or more Test monobehaviours all reference each other in a circular fashon ( I would set this up in the inspector), and unity will be able to save this just fine.

So the class has to be derived from ScriptableObject to be one that you can drag and drop in the editor - the only other editability is getting and setting the value of i, so that’s all you can do in the inspector.

Your editor code needs to use EditorUtility.SetDirty on the root object to indicate that you have made changes to it.

I had the same problem !!! … until today

I found out there’s a library that allows saving circular references using json

Code to save the model:
JsonSerializerSettings settings = new JsonSerializerSettings {
PreserveReferencesHandling = PreserveReferencesHandling.Objects
string json = JsonConvert.SerializeObject(gameData, Formatting.Indented, settings);
File.WriteAllText(jsonFile, json);

Code to load the model

    string json = File.ReadAllText(jsonFile);
    gameData = JsonConvert.DeserializeObject<GameData>(json);