Advertisement
LittleAngel

Undo Code

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