使用示例
创建命令
撤销系统基于命令模式,在使用前,您需要创建一个命令。在本示例中,我们创建一个名为 NameChangeCommand 的命令。
NameChangeCommand.cs
using UnityEngine.UIElements;
using winS.UnityEditor.Undo;
public class NameChangeCommand : IUndoCommand
{
public string info => "修改名称";
private readonly string oldName;
private readonly string newName;
private readonly TextField textField;
public NameChangeCommand(TextField textField, string oldName, string newName)
{
this.oldName = oldName;
this.newName = newName;
this.textField = textField;
}
public void Redo()
{
textField.SetValueWithoutNotify(newName);
}
public void Undo()
{
textField.SetValueWithoutNotify(oldName);
}
}
创建撤销系统
我们创建一个名为 PlayerDataEditor 的编辑器来模拟数据修改。 在OnEnable消息里,我们创建了 UndoSystem 的实例。
通过Unity菜单栏的 "Test/PlayerDataEditor", 您可以打开这个编辑器。 在Name输入框中输入一些文本,然后按下编辑器的撤销键(默认为Ctrl+Z)和重做键(默认为Ctrl+Y),您可以看到撤销系统已生效。
PlayerDataEditor.cs
using UnityEditor;
using UnityEngine.UIElements;
using winS.UnityEditor.Undo;
public class PlayerDataEditor : EditorWindow
{
private UndoSystem undoSystem;
[MenuItem("Test/PlayerDataEditor")]
private static void OpenWindow()
{
GetWindow<PlayerDataEditor>();
}
private void OnEnable()
{
undoSystem = new UndoSystem();
TextField nameField = new TextField("Name");
rootVisualElement.Add(nameField);
nameField.RegisterValueChangedCallback(changeEvent => undoSystem.AddCommand(new NameChangeCommand(nameField, changeEvent.previousValue, changeEvent.newValue)));
}
private void OnDisable()
{
undoSystem.Clear();
}
}