Version: 2021.1

EditorWindow.hasUnsavedChanges

切换到手册
public bool hasUnsavedChanges ;

描述

When set to true in a derived class, the editor will prompt the user to save unsaved changes if the window is about to be closed.

Set hasUnsavedChanges to true to prevent users from accidentally losing unsaved work. For hasUnsavedChanges to work, you must use it with EditorWindow.saveChangesMessage and override the EditorWindow.SaveChanges method. Once hasUnsavedChanges is enabled, the tile bar and docked tabs will update to show that the user needs to save their work. If the user closes the window without saving, a message box will pop up which prompts them to either save at that time, discard the charges or cancel.

// C# Example
// Script that demonstrates the unsaved changes API

using UnityEngine; using UnityEditor;

public class UnsavedChangesExampleWindow : EditorWindow { [MenuItem("Example/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 OnGUI() { saveChangesMessage = EditorGUILayout.TextField(saveChangesMessage);

EditorGUILayout.LabelField(hasUnsavedChanges ? "I have changes!" : "No changes.", EditorStyles.wordWrappedLabel); EditorGUILayout.LabelField("Try to close the window.");

if (GUILayout.Button("Create unsaved changes")) hasUnsavedChanges = true;

if (GUILayout.Button("Save")) SaveChanges(); }

public override void SaveChanges() { // Your custom save procedures here

Debug.Log($"{this} saved successfully!!!"); base.SaveChanges(); } }