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