此属性指定在检查器重建之前,编辑器是否提示用户保存或放弃未保存的更改。
将 hasUnsavedChanges 设置为 true 以提示用户保存或放弃未保存的更改。这有助于防止他们意外丢失未保存的工作。当您使用 hasUnsavedChanges 时,您还必须使用 EditorWindow.saveChangesMessage,并覆盖 EditorWindow.SaveChanges 和/或 EditorWindow.DiscardChanges 方法。当启用 hasUnsavedChanges 时,标题栏和停靠选项卡会更新以指示用户需要保存其工作。如果用户在未保存的情况下关闭 InspectorWindow、更改选择或进入播放模式,则会出现消息框,并提示他们保存、放弃更改或取消。
using UnityEngine; using UnityEditor;
[CreateAssetMenu] public class UnsavedChangesExampleSO : ScriptableObject {}
[CustomEditor(typeof(UnsavedChangesExampleSO))] public class UnsavedChangesExampleEditor : UnityEditor.Editor { void OnEnable() { saveChangesMessage = "This editor has unsaved changes. Would you like to save?"; }
void OnInspectorGUI() { saveChangesMessage = EditorGUILayout.TextField(saveChangesMessage);
EditorGUILayout.LabelField(hasUnsavedChanges ? "I have changes!" : "No changes.", EditorStyles.wordWrappedLabel); EditorGUILayout.LabelField("Try to change selection.");
using (new EditorGUI.DisabledScope(hasUnsavedChanges)) { if (GUILayout.Button("Create unsaved changes")) hasUnsavedChanges = true; }
using (new EditorGUI.DisabledScope(!hasUnsavedChanges)) { if (GUILayout.Button("Save")) SaveChanges();
if (GUILayout.Button("Discard")) DiscardChanges(); } }
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(); } }