I can’t work out why I’m getting this NullReferenceException from AssetDatabase.SaveAssets(). The scriptable object isn’t null, otherwise it wouldn’t reach the SaveAssets line.
Seems like there’s some kind of bug with the internal GameObjectInspector class in 2019.2. It’s not anything to do with your code as far as I can tell.
I’ve seen this exception completely unrelated to saving Assets. I too think this is some weird Unity bug. Does the asset actually gets saved or not when you see the error?
Correct. I took a stroll through the Unity Reference Source. A list access is missing a null check or the list isn’t getting created early enough or the method is getting incorrectly called after OnDisable. Couldn’t see a situation in which that could possibly be caused by the posted code.
I believe that’s because saving an asset triggers asset database update and this triggers inspector update and inspector update triggers preview invalidation, probably
I seem to be getting the exact same bug in 2018.3.8
I only made two changes before it appeared:
Started using Unity’s SettingsProvider class (2018.3+ only) - which seems incomplete and unmaintained despite being the new official settings system (c.f. the plethora of threads asking questions about why it doesn’t work with packages, etc. c.f. the fact that the official Unity docs give source code that cannot work, by definition! (and the author clearly never tried running )).
In order to support the above … switched code that was loaded one frame AFTER the Editor reloads assemblies (on Editor start, or on re-compile of C#), into running immediately during the Editor’s official mechanism for detecting reloads: the class-static-initializer.
I suspect that item 2 above is the cause. I can remember Unity having serious problems with their undocumented, poorly designed, startup routines going back at least as far as Unity 3.5 :).
If so … something to try for anyone else with this problem: re-evaluate what your trigger criteria are for calling SaveAssets(). If it’s anything related to Unity itself (e.g. an Editor callback), see if you can insert a 1 frame delay before doing the Save.
Not sure this is entirely related but as mentioned above, with the scene display being a part of the error, in my game view I get odd lines that shouldn’t exist. Almost like something glitched when previewing the scene in the game view. as I move the game view around or reload my scene, the lines jitter and replace themselves. Both the error and these visual cues came in at the same time for me.
I think this is correct. The workaround is to delay saving the asset until after the inspector has been updated, using EditorApplication.delayCall. For example: