Unity3D ver 5.3 Custom Editors 的 Undo 使用方式

Unity3D ver 5.3 Custom Editors 的 Undo 使用方式

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

 

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

*

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料