Advertisement
LittleAngel

Undo Code

Aug 9th, 2012
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. /* Notes
  2.  
  3. Add this to the end of a custom editor.
  4.  
  5. Make sure there is a member variable for thisTarget..
  6.  
  7. Make sure target code is in OnEnable()
  8.  
  9. Make sure CheckUndo(); is at the top of the OnInspectorGUI() method
  10.  
  11. Make sure you have: guiChange = true; as part of a button.
  12.  
  13. Make sure you have if (Gui.Changed) {guiChanged = true;} at the end of OnInspectorGUI;
  14.  
  15. Paste CheckUndo method at the end of the custom editor script.
  16.  
  17. */
  18.  
  19. private bool listeningForGuiChanges;
  20. private bool guiChanged;
  21. public TargetType thisTarget;
  22.  
  23. void OnEnable () {
  24. thisTarget = target as TargetType;
  25. // The rest of the OnEnable code...
  26. }
  27.  
  28. public override void OnInspectorGUI () {
  29. CheckUndo();
  30. // The rest of the EditorGUI code...
  31. if (GUILayout.Button( "SomeButton" ) ) {
  32. guiChanged = true;
  33. DoSomething();
  34. }
  35. if ( GUI.changed ) {
  36. guiChanged = true;
  37. }
  38. }
  39.  
  40. private void CheckUndo() {
  41. // Modified from code found here:
  42. // http://answers.unity3d.com/questions/50954/how-to-correctly-register-undos-in-custom-inspecto.html
  43. Event e = Event.current;
  44.  
  45. if (e.type == EventType.MouseDown && e.button == 0 || e.type == EventType.KeyUp && (e.keyCode == KeyCode.Tab)) {
  46. // When the LMB is pressed or the TAB key is released,
  47. // store a snapshot, but don't register it as an undo
  48. // (so that if nothing changes we avoid storing a useless undo)
  49. // Debug.Log("PREPARE UNDO SNAPSHOT");
  50. Undo.SetSnapshotTarget(thisTarget, "Message Displays");
  51. Undo.CreateSnapshot();
  52. Undo.ClearSnapshotTarget();
  53. listeningForGuiChanges = true;
  54. guiChanged = false;
  55. }
  56.  
  57. if (listeningForGuiChanges && guiChanged) {
  58. // Some GUI value changed after pressing the mouse.
  59. // Register the previous snapshot as a valid undo.
  60. // Debug.Log("REGISTER UNDO");
  61. Undo.SetSnapshotTarget(thisTarget, "Message Displays");
  62. Undo.RegisterSnapshot();
  63. Undo.ClearSnapshotTarget();
  64. listeningForGuiChanges = false;
  65. }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement