I have a series of classes that use public static instances of themselves to mimic the enum functionality offered by Java. As you might imagine, there were some tricks to serializing and deserializing those static instances, but I have that sorted out now. My test objects save and load from disk correctly.
Unfortunately, when I apply the
[Serializable] attribute to my character class, I run into several variations of the following error on startup:
NullReferenceException: Object reference not set to an instance of an object
Rethrow as TypeInitializationException: An exception was thrown by the type initializer for Namespace.DurationType
It appears that putting the
[Serializable] attribute on this particular class causes something on it to be executed before anything else in my codebase. This is very confusing to me, since the null error that is logged suggests that the static constructor on my enum classes has not been called properly.
Is there a way to force a certain script to be handled first by Unity? If so, I would expect I could force my static constructor to run before this weirdness occurs with the character class.
Note: none of the classes I’m serializing are derived from MonoBehaviour.
Update: The problem appears to be caused by Unity creating an instance of one of my classes before allowing its type initializer to be run. This is caused by having a script in the editor reference a class that uses my character object.
If I use a startup script to attach the character object dynamically, the problem goes away.
This is pretty clearly a Unity bug. Still looking for a better workaround than “script everything instead of using the editor”.