How do I detect that MonoBehaviour is modified in the Editor?

I have a MonoBehaviour which builds a procedural mesh. I want to make a preview of it in the Editor, so I need a couple of callbacks:

  • when it's dropped into Editor, so I can build the mesh for the first time
  • when some field is modified, so I can rebuild the mesh

Could you tell me if these callbacks are available and how they are called? Or tell me if I'm supposed to do this in some other way.

when it's dropped into Editor, so I can build the mesh for the first time

The callback you probably want is OnEnable and make sure the MonoBehavior is set to execute in the editor.

when some field is modified, so I can rebuild the mesh

There are no callbacks that track field changes. GUI.changed may be of use since it will trigger on changes to the inspector. But you may need to implement a custom inspector then use it in the OnInspectorGUI callback. (I haven't tried to use GUI.changed for a MonoBehaviour in the editor without a custom inspector.)

void OnInspectorGUI()
{

    // Implement field GUI controls here.

    // Check to see if any of the field GUI controls resulted in a change.
    if (GUI.changed)
    {
        // Call your function to rebuild of mesh.
        // E.g.: RebuildMesh();
        // Also, tell the Unity editor that the object has changed and
        // needs to be saved when the scene is saved.
        EditorUtility.SetDirty(target);
    }
}

See also: Extending the Editor -> Making a Custom Editor.

Another options is to use the OnValidate() method. It will fire if any value in the inspector has changed. It doesn’t tell you what has changed but with a few variables you could get the info you need.

This doesn’t require [ExecuteInEditMode]!