Serializing a class that contains a list of its own class

Hi all

So I have this issue where my custom editor tools are intended to fill a list of Point (a class Point). So I need to serialize it so that when I hit play it doesn’t lose the information. Problem is, Point class contains a list of Point called neighbors. So Unity runs out of memory because of how the inspector works, inside the each member of the list I want to save it has a list of point, which contains a list of point etc. I’m not sure if that will be a problem with the build, but regardless, I can’t live with that performance impact on the editor.

My solution is to nonserialize the list of Point inside Point, but then I need to reference these other points with an index system, which is a pain because any changes to the main list changes the indices, so I have to cycle through all of them to update their indices. Can anyone think of a better way to make reference to other objects in a long list?

If there is another way to not lose the information besides serialization, that would also be helpful. Maybe writing to a file, then reading the file in playmode? could that be done without serialization?

This case was actually one of the examples in the “Limitations of Unity serialization” post: Unity Blog

Scroll down to the “I want to serialize something that Unity doesn’t support” section to get their advice.

2 Likes

Thank you! That was extremely useful and fast.

Unfortunately my case is not exactly a tree like his example, so I can’t use this blindly. I’ll see if I can figure out what is going on exactly and see if I can make it work for me, otherwise I’ll need another solution.

Unity serialization does not serialize by reference, except for anything that is a UnityObject.

So if your class is a MonoBehaviour or something like that, and contains a list of its own type, then the serialization system will store ‘references’ when serialized.

But if it’s any other type, then they’re serialized by value. So if you have a class Test, with a list of Test. Well you get an infinite loop of fields. Your Test contains Tests that contain Tests that contain Tests and so on and so forth.

Most serialization engines don’t support this actually, because serialization is inherently a ‘by value’ process. This would be like having a struct with itself as a field member.

Oh boy, even if I made that work it wouldn’t work then. Thanks for the info! now I know exactly what must be done.