How to setup code so it can recompile without null exception while running

How do oyu setup code so it does not throw null exceptions when recompiled while running. I know this could be done in Unity 2.x and I suspect it still can be done. I know it had to do with setting up variables but don’t remember what had to be not used. Static variables? unserialised variables?

note: This is a duplicate question but previous question was only answered by someone who did not know about unity and just said it can’t be done. Please only answer “it can’t be done” if you understand how it used to be done and know that that will not work anymore.


When your code is recompiled, all class instances are destroyed, but things Unity knows how to serialize are serialized first and recreated afterwards. So your MonoBehaviours will get reattached to your GameObjects, and members that Unity can serialize will have their values preserved. Anything else will be null.

In some cases making more things serializable will help, but it’s not always practical - it depends on how complex your classes are. Some things are easier to recreate from scratch after the recompile, based on other members that were serialized. There’s no explicit notification, but I believe OnEnable gets called at this point, so you can put code in there to detect the problem (e.g. test something for null) and perform any fix-up you want to do, reconstructing whichever objects were lost.