- Home /
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.
Cheers, Grant
Answer by gfoot · Feb 01, 2014 at 11:21 AM
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.
Right - when I first started I didn't even know what serializing mean. So it's good to mention that as well. @OP: (basically) serializing something means storing that thing to disk (there's binary serialization, xml, soap, etc) - Deserializing something, is the opposite - it's loading an object into your app from disk.
I used to suffer from this too - but basically you just have to keep an eye out of what are the types that Unity serializes, and what it doesn't. Here, have a look.
If you have a variable of type X, assu$$anonymous$$g X is something that unity can serialize, if you set X's privacy to public, it will be serialized by default otherwise (private/protected) you should mock the field with [SerializeField].
Note that, if you want to have a private variable (hidden from inspector) to be serialized, mocking it with SerializeField will make it visible so you have to mock it with [HideInInspector]
Also, helps to read this.
Good luck :)