In this lesson, you will learn how to make your custom inspector tools feel like native Unity features by integrating the Undo system to ensure every change can be reversed with Ctrl+Z.
Why Manual Undo Matters
When you build a custom inspector, Unity doesn't automatically track changes you make to serialized fields via code. If you simply write target.myValue = newValue; inside an OnInspectorGUI() method, Unity won't know that this change is part of an undoable operation. If the user hits Ctrl+Z, nothing will revert, and you risk leaving your project in an inconsistent state or losing important data during iteration.
Registering Changes with Undo.RecordObject
To make your inspector tools professional and safe, you must notify the Undo system before you modify any data. The standard pattern is to use Undo.RecordObject(target, "Undo Message"). This tells Unity to capture the current state of the object so that it can restore it later if needed.
Here is how you implement it in a custom editor:
public override void OnInspectorGUI()
{
serializedObject.Update();
// The user interacts with a button or field
if (GUILayout.Button("Reset Settings"))
{
// 1. Tell Undo to record the target BEFORE changing it
Undo.RecordObject(target, "Reset Inspector Settings");
// 2. Now perform the modification
((MyScript)target).ResetValues();
// 3. Mark as dirty so Unity knows to save the change
EditorUtility.SetDirty(target);
}
}
The Workflow
- Record:
Undo.RecordObjectmust be called right before the modification logic. The string argument is the label that will appear in the Unity "Edit" menu (e.g., "Undo Reset Inspector Settings"). - Modify: Apply your logic to the data.
- Dirty: Call
EditorUtility.SetDirty(target)to ensure Unity recognizes that the object has changed and needs to be saved to disk.
By following this pattern, you provide a seamless experience where your custom tools respect the user's workflow, allowing them to experiment freely without the fear of permanent, accidental changes.
Key Takeaway: Always register your modifications with Undo.RecordObject before changing data in a custom inspector to ensure user actions are safely reversible.