I just had this field with certain class type that acted so $h!++y on me that I almost believed I had finally gotten insane from all those coding.
I’m talking about Unity C#. When the code runs after a domain reload, I find that this specific field always comes prefilled with “an instance of that class whose properties were the default values.” So every time when I change something in my code (which causes a domain reload,) this field becomes an instance of the class with default properties **without any outside interaction.** All my null guard code fails and what follow are thousands of null reference exceptions because my scripts tries to access the properties of that instance, which are null.
Turns out, it was maybe because the class in question was marked with [Serializable]. When I remove it, the behavior completely stops.
This behavior was so unexplainable in clear words that googling for such behavior was pure impossible. Like WAT. I don’t even know which of C# or Unity caused this weird $h!+ to happen.

  • 1
    Not sure how or why, but a serialized class should expect that to happen.

    It is used to save the state of that object in memory. After a domain refresh, the state is then recovered. (So it is not null anymore)

    You can find a walkthrough here :

  • 1
    Unity behaves weirdly with serialization and null references.
    Gotta know em quirks
Add Comment