在 Unity3D 的套件製作中, Editor 經常需要考慮進行 Undo Redo 的使用者操作.
參考: http://docs.unity3d.com/530/Documentation/ScriptReference/Undo.html
這裡筆記一下使用 Undo 的常用方式.
一般參數改變 (Undo Parameter change)
public Vector3 m_Point; // variable void OnSceneGUI() { Vector3 newPosition = Handles.PositionHandle(m_Point, Quaternion.identity); if(newPosition != m_Point) { Undo.RecordObject(this, "Move Point"); // register before assign new value m_Point = newPosition; // assign new value } }
增加實體的改變 (Undo created object)
void AddObject() { GameObject obj = new GameObject(); // <- create new object obj.name = "New Object" + obj.GetInstanceID(); // do what ever you want. CustomClass script = obj.AddComponent<CustomClass>(); // even add component Undo.RegisterCreatedObjectUndo(obj, "Create Curve " + obj.GetInstanceID()); // register the whole gameobject you created }
刪除物件的改變 (Undo delete object)
void RemoveObject_One() { Undo.DestroyObjectImmediate(obj.gameObject); } //////////////////////////////////////////// public List<CustomClass> m_ChildObjectList = new List<CustomClass>(); void RemoveObject_Two() { // Record the objects, variables, that will change in this action. // Method 1 Undo.RecordObject(m_ChildObjectList, "Remove Object"+ obj.GetInstanceID()); // Method 2 // Undo.RecordObjects(new object[] { // m_ChildObjectList, // another_invoke_variables, // another_invoke_variables, // another_invoke_variables, // }, "Remove Object"+ obj.GetInstanceID()); m_ChildObjectList.Remove(obj); // process change // only "Undo.DestroyObjectImmediate" can undo/redo the destroy object. Undo.DestroyObjectImmediate(obj.gameObject); }