Strange issue with "this" being lost by Unity?

I am trying to track down an intermittent bug that is driving me nuts.

I have a bit of code that is executed inside of a ScriptableObject asset. This code creates a subasset that is also a SO.

Simplified and sanitized code below:

public T CreateProperty<T>()
{
    T newProperty = ScriptableObject.CreateInstance<T>();
    AssetDatabase.AddObjectToAsset(newProperty, this);
   // .... snipped
}

Now the weird bug is that occosionally, and best I can tell completely randomly, when the AddObjecToAsset method runs, Unity will throw an error as shown below, but the super confusing part of this error is it is essentially claiming that the object running the code, “this” has been destroyed. Which seems impossible since it is the object running the code! Furthermore it still exists as I can see the asset in the project window.

Error: MissingReferenceException: The object of type ‘MainAsset’ has been destroyed but you are still rying to access it.

Now I know it is referring to “this” and not “newProperty” based on the type indicated in the error (which is not MainAsset in reality but that illustrates the point).

Anyone seen anything like this? It is driving me crazy.

This is eventually possible with unity. This error means the object in the c++ core, referred by unity engine object in question (MainAssset) was destroyed, but you trying to access it through UnityEngine.Object instance you have. The code presented here alone can’t be a reason for this. the problem is somewhere else. Are you using DestroyImmediate anywhere?

Not directly but this is part of a complex series of code that creates new assets in the project so i’m wondering if there is some flushing or something hat randomly is happening due to the asset creation process.

Like I said it only happens…sometimes.

Well I still don’t know why but I did manage to determine a pattern. It isn’t random. It only happens to the very first asset created after Unity has reloaded assemblies due to a code change.