Why does Undo not work correctly with my CustomEditor?

My Answers account is on the fritz at the moment.

When I press control+Z, ‘count’ drops down to the next-highest even number. It should just decrease by one. What am I doing wrong?

Here’s the object:

class Undoable extends Monobehaviour {
  var count : int;
}

Here’s its editor:

@CustomEditor(Undoable)

class UndoTest extends Editor {
	
	function OnInspectorGUI() {
		
		if ( GUILayout.Button("Add (" + target.count + ")") ) {
			Undo.RegisterUndo(target as Undoable,target.count.ToString());
			target.count = target.count + 1;
		}
	}
}

Clicking the button adds one to count. Pressing control-z, or using the Undo option from the menu, drops the count to the next highest even number (so if I add to 11, then undo, it’ll go to 10, then 8, then 6, etc.)

The problem is a lot worse in my actual class inspector. Undo doesn’t just skip a step, it drops straight back to the state of the object when the scene was last loaded.

Edit: Scratch that, it’s a magical mystery state somewhere between a prefab and the object with the broken prefab connection. Yaay. I’m sure there’s a complex logic error in that one somewhere.

As a bonus, thinking perhaps GUI was responsible for not following EditorGUI’s rules, I wrote a second method of both adding and undoing. Notice that the code is all new. I must be doing something really obviously wrong, or else be really bad at searching for ‘undo doesn’t work rite’.

@CustomEditor(Undoable)

class UndoTest extends Editor {
	var count : int; var propcount : SerializedProperty;
	function OnEnable() {
		propcount = serializedObject.FindProperty("count");
	}
	function OnInspectorGUI() {
		serializedObject.Update();
		
		if ( EditorGUILayout.Toggle("Add " + propcount.intValue, false, EditorStyles.miniButton) ) {
			propcount.intValue += 1;
		}
		
		serializedObject.ApplyModifiedProperties();
	}
}

This is holding up my development. Has no one ever encountered this? This seems like the sort of thing that would come up a lot.

This appears to be a bug that happens specifically on Windows. I’ve filed a bug report for it (case 486813, if you want to follow it up) and it will hopefully be fixed by the next release.

In the meantime you can perhaps look at this? http://wiki.unity3d.com/index.php?title=EditorUndoManager

I didn’t know there were an alternative way to get undo capabilities in a custom editor so I downloaded that and it’s been working perfectly for me this far. :slight_smile:

Well thanks! I feel much less dumb now. Still surprised I couldn’t find information on this. I’m guessing it’s a recent development?

AAAAAGGGGH still double-undoing. I was hoping to submit this to the Asset Store, and there aren’t any Macs nearby. :confused: