Initialization fails when I recompile, works otherwise

I’m looking for some “general principles” here, not a specific solution.

I have some code that uses a MonoBehaviour with a fair amount of static data shared across all object instances.

My code works 100% perfectly when I first load the scene. But every time I compile C#, whether or not I’ve touched the specific class in question, something is wonky with the serialization, and I lose a couple of Dictionary variables. If I run the game, my init logic picks up the need for init, and all is well. Stop the game, and things stay okay.

It’s only the recompile process that’s squashing my data variables. So… What is different about the way serialization works during recompile versus how it works when you start and stop the runtime or save and reload a scene?

Thanks for any general knowledge here. I’m asking for understanding of the principles involved, rather than a specific solution to my immediate problem, because I think this could be a useful learning moment for me. :slight_smile:

Unity doesn’t automatically serialize Dictionaries. They will basically get wiped out sort of randomly after recompiling. You can sort of get around it by saving it as a list of keys and a list of values, since Unity can automatically serialize Lists.

See: [Solved]How to serialize Dictionary with Unity Serialization System - Questions & Answers - Unity Discussions

If you change code, you cannot continue. You need to restart. If you want to not restart, you will have to write a bunch of extra code to make sure everything re-inits. Not worth the effort tbh.

Just accept that a change of code requires a game restart

Unity doesn’t serialize dictionaries, hashsets, generic classes(except List<>), you have to handle that yourself via ISerializationCallbackReceiver.

Any value that cannot be serialized upon deserialization will be reset (IIRC) to a default value. That’s why your dictionaries lose data. Serialization/deserialization occurs every time you rebuild the code.

Unity also doesn’t serialize state of coroutines.

Hey, all… I wanted to say thanks for the tips, which have really helped me understand the problem better. I am still deciding what to do about it, but you have given me some really good background understanding, which is what I was seeking. Understanding the problem is the hardest part of solving it!

I am sorry for the slow reply; I have been working crazy hours this week.