放弃对窗口内容的未保存更改。
覆盖 DiscardChanges() 以在关闭窗口时放弃未保存的工作。当用户关闭窗口时,编辑器会在内部调用此方法。编辑器调用此方法后,会提示用户放弃更改。当您覆盖此方法时,请调用基实现。否则,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(); } }