Unity常用命令模式详解

2020-01-05 10:11:39王冬梅


public class ColorChangeCommand : ICommand
{
  private Stack<Color> m_OriginColor = new Stack<Color>();
  private Color m_Color;
  private Material m_Material;
  
  public ColorChangeCommand(Color color, Material material)
  {
    m_Color = color;
    m_Material = material;
  }

  public void Execute()
  {
    m_OriginColor.Push(m_Material.color);
    m_Material.color = m_Color;
  }

  public void UnDo()
  {
    m_Material.color = m_OriginColor.Pop();
  }
}

五、移动命令脚本


public class MoveCommand : ICommand
{
  private Vector3 m_Offset;
  private Transform m_Object;

  public MoveCommand(Transform obj, Vector3 offset)
  {
    this.m_Object = obj;
    this.m_Offset = offset;
  }

  public void Execute()
  {
    m_Object.transform.position += m_Offset;
  }

  public void UnDo()
  {
    m_Object.transform.position -= m_Offset;
  }
}

六、转换命令脚本


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();
    }
  }
}

七、文字加载脚本


public class TextChangeCommand : ICommand
{
  private Stack<string> lastInfos = new Stack<string>();
  private IEnumerator<string> datas;
  private TextMesh m_Textmesh;

  public TextChangeCommand(TextMesh textMesh,ICollection<string> texts)
  {
    datas = texts.GetEnumerator();
    m_Textmesh = textMesh;
  }

  public void Execute()
  {
    if (!datas.MoveNext())
    {
      datas.Reset();
      datas.MoveNext();
    }
    lastInfos.Push(m_Textmesh.text);
    m_Textmesh.text = datas.Current;
  }

  public void UnDo()
  {
    m_Textmesh.text = lastInfos.Pop();
  }
}