拓展編輯器(十二)_Context菜單
阿新 • • 發佈:2018-11-03
修改 med mono man mon cati 組件 底層 ont
點擊組件中設置(鼠標右鍵),可以彈出Context菜單,我們可以在原有菜單中拓展出新的菜單欄,代碼如下所示:
using UnityEngine; using UnityEditor; public class Context菜單 { [MenuItem("CONTEXT/Transform/New Context 1")] public static void NewContext1(MenuCommand command) { //獲取對象名 Debug.Log(command.context.name); } [MenuItem("CONTEXT/Transform/New Context 2")] public static void NewContext2(MenuCommand command) { Debug.Log(command.context.name); } }
其中,[MenuItem("CONTEXT/Transform/New Context 1")]表示將新菜單擴展在Transform組件上。如果想拓展在別的組件上,例如攝像機組件,直接修改字符串中的Transform為Camera即可。如果想給所有組件都添加菜單欄,這裏改成Compoment即可。代碼效果如下:
除此以外,以上的設置也可以應用在自己的寫的腳本中。代碼如下:
using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif public class Context菜單2 :MonoBehaviour { public string contextName; #if UNITY_EDITOR [MenuItem("CONTEXT/Context菜單2/New Context 1")] public static void NewContext2(MenuCommand command) { Context菜單2 script= (command.context as Context菜單2); script.contextName = "hello world!"; } #endif }
這段代碼通過MenuCommand來獲取腳本對象,從而訪問腳本中的變量。同時使用了宏定義標簽,其中UNITY_EDITOR標識這段代碼只會在Editor模式下執行,發布後將會被剔除掉。效果如下:
當然,我們也可以在自己的腳本中這樣寫。如果和系統中的菜單名稱一樣,還可以覆蓋它。比如,這裏重寫了刪除組件的按鈕,這樣就可以執行自己的一些操作了:
[ContextMenu("Remove Comconent")] void RemoveComponent() { Debug.Log("RemoveComponent"); //等一幀再刪除自己 UnityEditor.EditorApplication.delayCall = delegate () { DestroyImmediate(this); }; }
編輯模式下的代碼同步時可能會有問題,比如上述DestroyImmediate(this)刪除自己的代碼時,會觸發引擎底層的一個錯誤。不過我們可以使用UnityEditor.EditorApplication.delayCall來延遲一幀調用。如果大家在開發編輯器代碼時發現類似問題,也可以嘗試延遲一幀再執行自己的代碼。
拓展編輯器(十二)_Context菜單