How to destroy a component from an OnValidate() event?

It seems that I cannot destroy a component on an OnValidate() event? Destroy doesn’t work and neither does DestroyImmediate, as seen in the logs in the above image…

The use case:
I’m trying to destroy some specific components in the current object that I don’t want to be added by mistake by the game designer (or even by me).

You can defer the “Destroy” to the next editor update tick.
Something like this

private void OnValidate()
{
    if(whatever)
          EditorApplication.update += HandleDeletion;
}

private void HandleDeletion()
{
          EditorApplication.update -= HandleDeletion;    
          Destroy(theCmpYouWantToDestroy);
}

From your OnValidate, hook your closure to EditorApplication.delayCall event. No need to unsubscribe, it’s cleared automatically after invoke.

‘EditorApplication.delayCall += ()=> {Destroy(component);};’

Or rather, DestroyImmediate

This is what you should do:

#if UNITY_EDITOR
void OnValidate ()
{
    if( Application.isPlaying )
    {
        Destroy( obj );
    }
    else
    {
        DestroyImmediate( obj );
    }
}
#endif