制作好界面之后就可以来实现具体的脚本编辑了,分别创建好接口ICommand,配制脚本RemoteLoader和执行脚本RemoteControl,结构如下:
在Commonds中,分别编写了用于移动,旋转,颜色,文字的脚本
这样一来,就可以实现一个可撤销的命令模式了,效果如下所示:
其中用于保存undo方法和具体怎么undo都是使用Stack来实现的,下面分别是部分代码实现 :
一、接口
public interface ICommand
{
void Execute();
void UnDo();
}
二、执行器
public class RemoteControl : MonoBehaviour {
public Button ctrlBtn;
public Button undoBtn;
public Text ctrlName;
private ICommand icommand;
public Stack<UnityAction> undoFunctions = new Stack<UnityAction>();
void Awake(){
ctrlBtn.onClick.AddListener(OnCtrlBtnClicked);
undoBtn.onClick.AddListener(OnUnDoBtnClicked);
}
public void SetText(string textinfo)
{
ctrlName.text = textinfo;
}
public void SetCommond(ICommand icommand)
{
this.icommand = icommand;
}
/// <summary>
/// 执行
/// </summary>
public void OnCtrlBtnClicked()
{
if (icommand != null)
{
icommand.Execute();
undoFunctions.Push(icommand.UnDo);
}
}
/// <summary>
/// 撤销
/// </summary>
private void OnUnDoBtnClicked()
{
if (undoFunctions.Count > 0)
{
undoFunctions.Pop().Invoke();
}
}
}













