通過反射調用Unity編輯器提供的各種功能
阿新 • • 發佈:2018-10-12
代碼 ndt 就是 分享 uil ons uila 方式 引用關系
Unity編輯器功能豐富易上手,其實編輯器提供的大多數菜單操作,在代碼裏面都是能夠找到對應接口的,但是這些接口都沒有對我們開放,怎麽辦?
很簡單,直接使用反射調用即可。
首先使用Reflector或ILSpy將UnityEditor和UnityEngine進行反編譯(有源碼的可以直接查看源碼更好),然後在裏面找你需要的功能即可,unity的底層代碼命名是非常規範的,多數功能都能直觀的找到:
下圖中是Hierarchy視圖中一些操作函數,怎麽樣,是不是很直觀:
怎麽調用這些函數呢,下面展示了static function和member function的調用方式,參考著用即可:
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; public class DIYEditor : EditorWindow { private static EditorWindow window; [MenuItem("DIY/SelfEditor")] public static void Execute() { if (window == null) window= (DIYEditor)GetWindow(typeof(DIYEditor)); window.minSize = new Vector2(300, 300); window.Show(); } private void OnGUI() { if (GUILayout.Button("Project.DuplicateSelectedAssets", GUILayout.Height(50))) { ProjectDuplicate(); }if (GUILayout.Button("Hierarchy.DuplicateSelectedAssets", GUILayout.Height(50))) { HierarchyDuplicate(); } if (GUILayout.Button("GameView.SizeSelection", GUILayout.Height(50))) { HierarchyDuplicate(); } } // 拷貝Project視圖中的某個Prefab private void ProjectDuplicate() { var gvWndType = typeof(Editor).Assembly.GetType("UnityEditor.ProjectWindowUtil"); var duplicate = gvWndType.GetMethod("DuplicateSelectedAssets", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); duplicate.Invoke(null, null); } // 拷貝Hierarchy視圖中的某個Prefab,優點:(1)速度快(2)保持引用關系。在代碼中Instantiate會丟失引用,並且速度很慢 private void HierarchyDuplicate() { var gvWndType = typeof(Editor).Assembly.GetType("UnityEditor.SceneHierarchyWindow"); var gvWnd = EditorWindow.GetWindow(gvWndType); var duplicateSelectedFunc = gvWndType.GetMethod("DuplicateGO", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); duplicateSelectedFunc.Invoke(gvWnd, null); } // 手動設置Game視圖的分辨率,可以用來在編輯態下動態改變runtime分辨率 public static void SetGameView(int index) { var gvWndType = typeof(Editor).Assembly.GetType("UnityEditor.GameView"); var gvWnd = EditorWindow.GetWindow(gvWndType); var SizeSelectionCallback = gvWndType.GetMethod("SizeSelectionCallback", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); SizeSelectionCallback.Invoke(gvWnd, new object[] { index, null }); } }
總之,編輯器功能強大,皆能為我所用,方法就是反射,以上!
通過反射調用Unity編輯器提供的各種功能