Null references are assigned with a default instance after scripts have reloaded

Issue #283 resolved
Nicolás Ezcurra created an issue

When a field serialized by Odin is set to null and the project recompiles, it's assigned a new instance instead of staying as null.

Before reload:

ScreenShot_20180209172432.jpeg

After reload:

ScreenShot_20180209172355.jpeg

Comments (5)

  1. mSkull001

    I believe this is caused by Unity will serialize any field not marked with NonSerialized before a reload. Fx so that a game state can be kept. After the reload Unity will then deserialize these fields, and add a default value to them because Unity doesn't support null values in serialization.

    To get around this just add the NonSerialized attribute along with the OdinSerialize attribute to stop Unity from serializing the fields between reloads. You can also remove the Serializable attribute from the class definition, as Unity won't serialize it classes without that attribute either, but Odin will.

  2. Max Wrighton

    I was having the same issue just this week. Specifically what was throwing me off was that only some (not all) of my scene objects would have their null references assigned.

    So if I had 3 object all with the same monobehaviour attached only 1 or 2 of them would have thir null class assigned on script recompile. The affected object seemed consistent during a session but would change if I closed and reopened the project. Adding the NonSerialized attribute has fixed the issue and I will be more careful in the future, but I assumed that because my class member variable was private I wouldn’t need to add NonSerialized as well.

    @mSkull001 Would there be a way to flag this issue in the serialisation debugger? The output I was getting with and without the added NonSerialized attribute was (almost) the same. Odin is serialising the member, not Unity.

  3. Log in to comment