一:功能
1.實例化
//設置插件在菜單欄的位置 和快捷鍵 [MenuItem("YCC's Tools/模型更改/更改父物體和測量長度 %W")] //實例化窗體 static void Init() { myTools window = (myTools)EditorWindow.GetWindow(typeof(myTools)); window.titleContent.text = "更改父物體/測長"; window.Show(); }
2.選項卡制作
//用GUI畫出窗體的空間布局 void OnGUI() { toolbarOption = GUILayout.Toolbar(toolbarOption, toolbarTexts); switch (toolbarOption) { case 0: fnChangeParent(); break; case 1: fnLength(); break; } }
3.多個物體更改模型父物體
void fnChangeParent() { GUILayout.BeginHorizontal("box"); GUILayout.Label("父物體:", EditorStyles.boldLabel); ObjParent = EditorGUILayout.ObjectField(ObjParent, typeof(Transform)) as Transform; GUILayout.EndHorizontal(); GUILayout.BeginHorizontal("box"); iChildCount = Selection.transforms.Length;//獲取當前鼠標選中的物體個數 if (Selection.transforms.Length > 0) { GUILayout.Label("當前選中子物體個數:"+iChildCount, EditorStyles.boldLabel); if (GUILayout.Button("應用")) { if (ObjParent != null) { for (int i = 0; i < iChildCount; i++) { if (Selection.transforms[i].parent != ObjParent) Selection.transforms[i].parent = ObjParent; } EditorUtility.DisplayDialog("提示", "已更換父物體", "確定");//顯示對話框 DisplayDialog (title : string, message : string, ok : string, cancel : string = "") : bool } else this.ShowNotification(new GUIContent("當前沒有父物體!"));//顯示通知 } } else GUILayout.Label("當前沒有選中子物體" , EditorStyles.boldLabel); GUILayout.EndHorizontal(); }
4.測量兩個物體在場景中的距離
void fnLength() { GUILayout.BeginHorizontal("box"); GUILayout.Label("測量基准物體1:", EditorStyles.boldLabel); T1 = EditorGUILayout.ObjectField(T1, typeof(Transform)) as Transform; GUILayout.EndHorizontal(); GUILayout.BeginHorizontal("box"); GUILayout.Label("測量參考物體2:", EditorStyles.boldLabel); T2 = EditorGUILayout.ObjectField(T2, typeof(Transform)) as Transform; GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); if (T1 != null && T2 != null) { Debug.DrawLine(T1.position, T2.position, Color.red); //if (GUILayout.Button("查 尋")) //{ fDistance = Vector3.Distance(T1.position, T2.position); //} GUILayout.Label("距離:", EditorStyles.boldLabel); EditorGUILayout.FloatField(fDistance, EditorStyles.boldLabel); } GUILayout.EndHorizontal(); }
二:注意
1.重繪
//在OnInspectorUpdate上調用重繪,因為它在窗口上較少重繪,就好象是OnGUI/Update void OnInspectorUpdate() { Repaint();//重繪 }
2.錯誤
出現錯誤: Invalid editor window UnityEditor.FallbackEditorWindow 解決方法:Layout-> Revert Factory Settings