Using the Undo.IncrementCurrentEventIndex allows your editor scripts to undo a single action rather then have unity undo many actions that may have occurred in rapid succession. Place the code below into a “Editor” folder for it to run.
The “create object” button will create 10 cubes and call Undo.RegisterCreatedObjectUndo for each of them. Click this button then press ctrl+z to undo all of the objects that were created.
The second button “create single object” will also create 10 cubes but will also call the Undo.IncrementCurrentEventIndex method notifying unity that each object that is created should have a separate undo action. Click “create single object” to create 10 cubes then press ctrl+z to undo each object creation individually.
NOTE: At the time of this writing the unity documentation does not have information on the Undo.IncrementCurrentEventIndex method and searching for it also comes back with zero results.
using UnityEngine;
using UnityEditor;
public class UndoTest : EditorWindow
{
public void OnGUI()
{
if (GUILayout.Button("create object"))
{
this.Create(false);
}
if (GUILayout.Button("create single object"))
{
this.Create(true);
}
GUILayout.Label("use ctrl+z to undo each action");
}
private void Create(bool single)
{
for (int i = 0; i < 10; i++)
{
if (single)
{
Undo.IncrementCurrentEventIndex();
}
var obj = GameObject.CreatePrimitive(PrimitiveType.Cube);
obj.transform.position = new Vector3(Random.Range(-10, 10), Random.Range(-10, 10), Random.Range(-10, 10));
Undo.RegisterCreatedObjectUndo(obj, "create " + obj.name);
}
}
[MenuItem("CBX/UndoTest")]
public static void ShowWindow()
{
GetWindow<UndoTest>("UndoTest").Show();
}
}