Unity教程之-Unity3d开发中编辑器Editor的undo撤销操作

 

在Unity3d编辑器扩展中,常常需要兼容Undo的操作即:Cmd/Ctrl + z。在Unity3d对应的接口Undo.RecordObjects可以完成这项工作。

封装

由于它的参数需要我们操作对象的组件,我为他封装了一个操作类。通过托管的方式调用。

实现

实现函数如下:


using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;

/*
Usage:
var go = Selection.activeTransform;
UndoOperate bc = new UndoOperate("batch Operate");
bc.Add(go,()=>{
go.localPosition = new Vector3(1,2,1);
go.localScale = new Vector3(1,2,1);
});

var comp = go.GetComponent<Test>();
bc.Add(comp,()=>{
comp.str= "Hello SongYang";
});
bc.Flush();
*/

public class UndoOperate {
public delegate void Callback();
List<Object> targetList = new List<Object>();
List<Callback> callList = new List<Callback>();
string m_name;

public UndoOperate(string name) {
m_name = name;
}

public void Add(Object obj,Callback call) {
targetList.Add(obj);
callList.Add(call);
}

public void Flush() {
Undo.RecordObjects(targetList.ToArray(),m_name);
foreach(var each in callList) {
each();
}
}
};

好了,本篇unity3d教程到此结束,下篇我们再会!