此属性指定在窗口关闭之前,编辑器是否提示用户保存或丢弃未保存的更改。
将 hasUnsavedChanges 设置为 true 以提示用户保存或丢弃未保存的更改。这有助于防止他们意外丢失未保存的工作。当使用 hasUnsavedChanges 时,还必须使用 EditorWindow.saveChangesMessage,并覆盖 EditorWindow.SaveChanges 和/或 EditorWindow.DiscardChanges 方法。当 hasUnsavedChanges 启用时,标题栏和停靠选项卡将更新以指示用户需要保存其工作。如果用户在未保存的情况下关闭窗口,则会出现一个消息框,提示他们保存、丢弃更改或取消。
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(); } }