Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Undo" after editing objects in a custom editor

I've made a custom editor (extends EditorWindow). This editor allows to edit the selected objects.

The problem is that after I press a button on the editor panel, pressing CTRL/CMD+Zdoes nothing, it's not tracked in the history.

Is there some command that would enable to trace actions triggered from within a custom editor panel?

like image 281
Creative Magic Avatar asked Jun 18 '26 14:06

Creative Magic


1 Answers

You can do that but since unity doesn't automatically keeps track of objects modified by scripts, you have to inform the editor which object to record. You can rely on Unity's undo system for all serialized properties.

The steps are:

  1. use Undo.RecordObject to track an object before modifying it
  2. modify a serializedproperty of the object
  3. use EditorUtility.SetDirty to flag the object as modified

Here's a simple example:

public class TestWindow : EditorWindow {

    static Transform anObjTransform;
    void OnGUI() 
    {

        anObjTransform = EditorGUILayout.ObjectField ("selected object", anObjTransform, typeof(Transform), true) as Transform;

        if (anObjTransform != null && GUILayout.Button("MOVE RIGHT"))
        {
            Undo.RecordObject(anObjTransform, "move");
            anObjTransform.Translate(anObjTransform.right * 10f);

            EditorUtility.SetDirty(anObjTransform);
        }
    }
    [MenuItem ("Test/Test Window")]
    private static void Init () {
        EditorWindow.GetWindow<TestWindow> ();

    }
}
like image 196
Heisenbug Avatar answered Jun 22 '26 18:06

Heisenbug



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!