開發到中後期時,物件、介面一定會有很多,這時如果想要一次改變許多物體,例如:全部介面的按鈕事件設定、物件階層改變、特定 Component 設定、增加等等,如果使用手動的方式,會非常沒有效率,這時就可以使用 Editor Script 依據需求彈性修改物件。
本系列其他文章
使用環境 與 版本
- Window 7
- Unity 5.2.4
怎麼取得 Scene 中物體?
- 透過 Selection 取得選中的物體
- 使用 GameObject.FindXXX 相關方法找尋物體
- 透過特定物件,取得特定物件下的所有子物件,等等過濾方式
實做
需求 (此處簡單舉例,實際情況更為複雜)
1.尋找所有子物件中名稱為 Player 的物件
2.將 Player 的 Collider enabled false
3.在 Player 下增加一個子物件
4.同時子物件名稱命名為 Player Child
開始實作
1.目前物體階層

2.實作 Editor Script
A.使用 Selection 方式
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | using UnityEngine; using UnityEditor; public class ModifyBySelect {     [MenuItem("Modify/ModifyBySelect")]     public static void BySelect()     {         if (Selection.activeGameObject != null)             Modify(Selection.activeGameObject.transform);     }     static void Modify(Transform parent)     {         Transform trans = null;         for (int i = 0; i < parent.childCount; i++)         {             trans = parent.GetChild(i);             if (trans.childCount > 0)                 Modify(trans);             if (trans.name == "Player")             {                 trans.GetComponent<BoxCollider>().enabled = false;                 GameObject go = new GameObject("Player Child");                 go.transform.SetParent(trans);                 Debug.Log(trans);             }         }     } } | 
Line 6:實作 unity menu
Line 10:取得目前 Scene 中選中物件
Line 19:依序取出子物件
Line 21~22:如果子物件下還有物件,使用遞迴再次呼叫
Line 25:判斷 GameObject Name
Line 27:修改 BoxCollider enabled
Line 29~30:建立物件、設定階層
B.使用 GameObject.FindXXX 方式
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | using UnityEngine; using UnityEditor; public class ModifyByFind {     [MenuItem("Modify/ModifyByFind")]     public static void ByFind()     {         Modify(GameObject.FindObjectsOfType<Transform>());     }     static void Modify(Transform[] trans)     {         for (int i = 0; i < trans.Length; i++)         {             if (trans[i].name == "Player")             {                 trans[i].GetComponent<BoxCollider>().enabled = false;                 GameObject go = new GameObject("Player Child");                 go.transform.SetParent(trans[i]);                 Debug.Log(trans[i]);             }         }     } } | 
Line 6:實作 unity menu
Line 9:尋找 Scene 中類型為 Transform 的物件
Line 16:判斷 GameObject Name
Line 18:修改 BoxCollider enabled
Line 20~21:建立物件、設定階層
3.點選選單執行方法

4.結果

後記
經由 Editor Script 我們可以彈性修改多個物體,而不是使用手動的方式選取修改,進而提升開發效率,甚至可以根據不同需求與規格製作 Editor Window 工具。
參考資料
- Unity – Scripting API: GameObject
- Unity – Scripting API: Selection
- Unity – Scripting API: EditorWindow
歡迎轉載,並註明出處 !
 
	 
								 
								 
								 
								
 k79k06k02k@gmail.com
  k79k06k02k@gmail.com