对窗口内容执行保存操作。
当使用EditorWindow.hasUnsavedChanges 属性时,重写 SaveChanges(),以便在关闭窗口时用户不会丢失未保存的工作。编辑器在用户关闭窗口时也会在内部调用此方法。调用后,编辑器会提示用户保存更改。重写此方法时,请务必调用基实现,否则EditorWindow.hasUnsavedChanges 属性不会重置为 false。请注意,如果编辑器有多个提示用户保存其更改的提示,则编辑器会将此方法作为需要保存的更改列表的一部分进行调用。如果此方法引发异常,Unity 会取消所有剩余提示的保存过程。在这种情况下,您会发现一个错误消息,其中包含在对话框中显示的异常消息。
using UnityEngine; using UnityEditor; using UnityEngine.UIElements; public class UnsavedChangesExampleWindow : EditorWindow { [MenuItem("Examples/Editor Window With Unsaved Changes")] static void Init() { UnsavedChangesExampleWindow window = (UnsavedChangesExampleWindow)EditorWindow.GetWindowWithRect(typeof(UnsavedChangesExampleWindow), new Rect(100, 100, 400, 400)); window.saveChangesMessage = "This window has unsaved changes. Would you like to save?"; window.Show(); } void CreateGUI() { var label = new Label(); label.text = hasUnsavedChanges ? "I have changes!" : "No changes."; rootVisualElement.Add(label); var buttonCreate = new Button(); buttonCreate.text = "Create unsaved changes"; buttonCreate.clicked += () => { hasUnsavedChanges = true; Debug.Log($"{this} has unsaved changes!!!"); }; rootVisualElement.Add(buttonCreate); var buttonSave = new Button(); buttonSave.text = "Save"; buttonSave.clicked += () => SaveChanges(); rootVisualElement.Add(buttonSave); var buttonDiscard = new Button(); buttonDiscard.text = "Discard"; buttonDiscard.clicked += () => DiscardChanges(); rootVisualElement.Add(buttonDiscard); } public override void SaveChanges() { // Your custom save procedures here Debug.Log($"{this} saved successfully!!!"); base.SaveChanges(); } public override void DiscardChanges() { // Your custom procedures to discard changes Debug.Log($"{this} discarded changes!!!"); base.DiscardChanges(); } }