- Home /
How to properly handle Undo events in custom inspector?
Hey all, Im attempting to properly handle Undo-able changes in my custom inspector. Basically I have a monobehavior class (MySettings.cs) and a custom inspector for it (MySettingsInspector.cs).
I have a BeginChangeCheck() block, within which Im using Undo.RegisterCompleteObjectUndo(Settings) before applying the change to my Settings object. When the undo is performed, the value that was changed (a bool in this case) reverts properly, however the effect that that bool had is not reverted. The bool here is supposed to indicate whether or not the Settings object should show / hide a mesh. Despite the inspector value for this bool being reverted to its previous value, the visibility of the mesh is not affected, i.e. the changed bool value isnt propagated back to the Settings object. Heres some example code, all of which is inside the OnInspectorGUI() method.
// Toggle preview mesh visibility
EditorGUI.BeginChangeCheck();
ShowPreviewMesh = EditorGUILayout.Toggle("Show Preview Meshes", Settings.ShowPreviewMesh);
if(EditorGUI.EndChangeCheck())
{
Undo.RegisterCompleteObjectUndo(Settings, "Change show preview mesh");
Undo.FlushUndoRecordObjects();
Settings.ShowPreviewMesh = ShowPreviewMesh;
shouldRefresh = true;
}
if (shouldRefresh)
{
Settings.ApplySettings();
}
In this example, Settings is a class variable in MySettingsInspector.cs declared via
MySettings Settings = target as MySettings;
ShowPreviewMesh is a class variable of type bool in MySettingsInspector.cs.
The Settings.ApplySettings() function called at the end is a method in MySettings.cs that actually updates the object based on its current variables so that those values are reflected in the editor.
Can anyone give me some guidance on how to properly handle Undo events within the editor? My guess is that I need to call the ApplySettings() function when an Undo event occurs, but im not sure how to subscribe to the undoRedoPerformed callback in a custom editor script. Ive also tried using the Undo.RecordObject(Settings) with no luck :(
Any help is appreciated! Thanks
Your answer
Follow this Question
Related Questions
How to record hideFlags for Undo/Redo 0 Answers
Custom Inspector Color Spacer 1 Answer
How to show type text in EditorGUI.ObjectField? 1 Answer
BeginChangeCheck & EndChangeCheck not working? 1 Answer
CustomPropertyDrawer with UnityEvent 1 Answer