How to change script load order? (Serialization problem)

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
Namespace.DurationType..cctor ()
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”.

Yes there is…in fact you can make all scripts go in what order you want.I was experiencing a similar issue.
GO to EDIT->Project Settings->Script Execution Order and there you can add or remove what script goes first from top to bottom. :slight_smile:

Little late, but… Another solution would be to use Awake, instead of Start, since this is handle before any Start function, according to the monobehaviour lifecycle diagram.