Editor DestroyImmediate Remove component via script

My issue: I would like to add a component dynamically at Design/Editor Time if a checkbox is on and remove it if checkbox is off.

My code: Component1 uses [CustomEditor(typeof(Component1))] and Component2 uses [CustomEditor(typeof(Component2))]

ObjSceneComp is target of Component1 Inspector GUI.

if(CheckboxComponent1) {
            //if no Component2 added
            if(Component2Exists== false) {
                ObjSceneComp.gameObject.AddComponent<Component2>(); 

            }
        }
        else {
            if(Component2Exists== true) {
                DestroyImmediate( ObjSceneComp.gameObject.GetComponent<Component2>());  
            }
        }
}

It all works fine, but I always get this error: MissingReferenceException: The object of type 'EKISharedDataComponent' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.

If I take instead of Component2 an normal script without a CustomEditor behind Unity is going to crash.

I found another solution for this… If a custom inspector removes a component on the same game object, during the same iteration of drawing the inspector, Unity will encounter the removed component and error trying to draw it.

Using EditorGUIUtility.ExitGUI() will stop the execution of the current draw iteration, starting over from the top, at which point the removed component will not be attempted to be drawn.

I solved it myself:

You have to hide it it via a flag from your script. That flag you have to use for (un-)hiding in OnInspector function. If the component is hidden, then you can do the the DestroyImmediate as far as you have no scripts or other comps, which access your current component.

The problem is that the component is still visible in the inspector. Instead of calling

DestroyImmediate(CharacterDecal);

Use:

CharacterDecal.hideFlags |= HideFlags.HideInInspector;
DestroyImmediate(CharacterDecal);

This worked for me on Unity 5.5.3f1

Edit: Oh this doesn’t work: seems I tested it in play-mode.

If you can live with not having the component in the editor, you could set

CharacterDecal.hideFlags |= HideFlags.HideInInspector;

immediately when you created the component. The problem arises, because in the same frame the inspector is draw, it still holds a reference. So your component should be hidden already in the frame before you destroy it, or there should be a way to correctly notify the inspector, which I found not. Some users say to use UnityEngine.GUIUtility.ExitGUI () which throws an exception, but it is an internal function only and only has effect when in the GUI drawing routine I suspect.

But before all of these things, first try restarting your computer. I did that, and it worked…