对编辑器内容执行保存操作。
当使用 Editor.hasUnsavedChanges 属性时,重写 SaveChanges(),以便用户在关闭窗口时不会丢失未保存的工作。编辑器在用户关闭窗口时也会在内部调用此方法。调用后,编辑器会提示用户保存更改。重写此方法时,请务必调用基实现,否则 Editor.hasUnsavedChanges 属性不会重置为 false。请注意,如果编辑器有多个提示用户保存更改,则编辑器会将此方法作为需要保存的更改列表的一部分进行调用。如果此方法抛出异常,Unity 会取消所有剩余提示的保存过程。在这种情况下,您将在对话框中找到带有异常消息的错误消息。
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?"; }
public override 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(); } }