Unity命令模式, 实现撤销/反撤销

可以实现记录移动的位置, 撤销和反撤销

先上图:

记录1右
记录2上
记录3上
丢弃3上
记录3左
在这里插入图片描述

说思路:

每一步操作都是一个"命令"
用列表记录"命令"

"命令"包含新坐标和旧坐标
撤销, 即移动到旧坐标
反撤销, 即移动到新坐标

如果, 撤销后, 执行了新的操作, 则丢弃原始记录

贴代码:

挂在方块上就能运行

using System.Collections.Generic;
using UnityEngine;

public class Command
{
    Vector3 _oldPos, _newPos;
    Transform _tr;

    public Command(Transform tr, Vector3 oldPos, Vector3 newPos)
    {
        _tr = tr;
        _oldPos = oldPos;
        _newPos = newPos;
    }

    public void Do()
    {
        _tr.position = _newPos;
    }
    public void UnDo()
    {
        _tr.position = _oldPos;
    }
}

public class CommandPattern : MonoBehaviour
{
    int curIndex = -1;
    List<Command> commands = new List<Command>();

    void AddCommand(Command com)
    {
        if (curIndex < commands.Count - 1)
        {
            for (int i = commands.Count - 1; i > curIndex; i--)
            {
                commands.RemoveAt(i);
            }
            print("丢弃已记录的操作");
        }
        com.Do();
        commands.Add(com);
        curIndex = commands.Count - 1;
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.W))
        {
            Command com = new Command(transform, transform.position, transform.position + Vector3.up);
            AddCommand(com);
            print("上");
        }
        else if (Input.GetKeyDown(KeyCode.S))
        {
            Command com = new Command(transform, transform.position, transform.position + Vector3.down);
            AddCommand(com);
            print("下");
        }
        else if (Input.GetKeyDown(KeyCode.A))
        {
            Command com = new Command(transform, transform.position, transform.position + Vector3.left);
            AddCommand(com);
            print("左");
        }
        else if (Input.GetKeyDown(KeyCode.D))
        {
            Command com = new Command(transform, transform.position, transform.position + Vector3.right);
            AddCommand(com);
            print("右");
        }
        else if (Input.GetKeyDown(KeyCode.Z))
        {
            if (curIndex >= 0)
            {
                commands[curIndex].UnDo();
                curIndex--;
                print("撤销");
            }
            else
            {
                print("已最旧, 无法再撤销啦");
            }
        }
        else if (Input.GetKeyDown(KeyCode.Y))
        {
            if (curIndex < commands.Count - 1)
            {
                curIndex++;
                commands[curIndex].Do();
                print("反撤销");
            }
            else
            {
                print("已最新, 无法再反撤销啦");
            }
        }
    }
}
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值