- Home /
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.
Answer by SteveFSP · Dec 23, 2010 at 04:23 PM
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.
While I can't find any other way of noticing when an object is instantiated, I still find having a custom script on the host object a bit awkward. Is there no other way to know if an object is added (from the editor scripts)?
Could you tell me which method on my $$anonymous$$onoBehaviour will be called after this "EditorUtility.SetDirty(target);"?
Paulius: I've updated the example to be more plain. Calling SetDirty is for the benefit of the Unity Editor only. It lets the editor know the target has changed and needs to be saved.
Answer by inewland · Mar 14, 2015 at 12:47 AM
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]!
Your answer
Follow this Question
Related Questions
Editor script - any callback when target is first instantiated? 1 Answer
before and after apply prefab changes callback 0 Answers
Unity Editor crashing when editing scripts referenced from GameObjects 1 Answer
Save scene event when the user save the scene in the editor 1 Answer
The Script Equivilent of dragging a hierarchy of meshes over a preexisting prefab? 0 Answers