前面已經寫了三篇:
今天寫第四篇,擴展自己的自定義組件。
通常我們使用繼承自 Editor 的自定義編輯器類,來擴展自己的組件的檢視面板和編輯器,並配合 CustomEditor 特性語法,附加該編輯器到一個自定義組件。
首先我們先定義一個組件 Player:
1 using UnityEngine; 2 3 public class Player : MonoBehaviour 4 { 5 public int armor = 80; //護甲 6 public int attack = 100; //攻擊力 7 }
一個簡單的 Player 組件,有護甲和攻擊力兩個屬性,掛載后,效果如下:
接下來我們對 Player 進行擴展,代碼如下:
using UnityEngine; using UnityEditor; [CustomEditor(typeof(Player))] public class EditorTest : Editor { public override void OnInspectorGUI() { var _target = (Player)(serializedObject.targetObject); _target.armor = EditorGUILayout.IntSlider("護甲", _target.armor, 0, 100); ProgressBar(_target.armor / 100f, "護甲"); _target.attack = EditorGUILayout.IntSlider("攻擊力", _target.attack, 0, 100); ProgressBar(_target.attack / 100f, "攻擊力"); } private void ProgressBar(float value, string label) { Rect rect = GUILayoutUtility.GetRect(18, 18); EditorGUI.ProgressBar(rect, value, label); EditorGUILayout.Space(); } }
效果圖:
是不是感覺漂亮了很多,直觀了很多。這樣我們就可以把很多UI控件擴展到我們的組件上,顯得高大上。
實效上面這種效果,還有另外一種方法:
using UnityEngine; using UnityEditor; [CustomEditor(typeof(Player))] public class EditorTest : Editor { private SerializedProperty attack; private SerializedProperty armor; void OnEnable() { attack = serializedObject.FindProperty("attack"); armor = serializedObject.FindProperty("armor"); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUILayout.IntSlider(armor, 0, 100, new GUIContent("護甲")); ProgressBar(armor.intValue / 100f, "護甲"); EditorGUILayout.IntSlider(attack, 0, 100, new GUIContent("攻擊力")); ProgressBar(attack.intValue / 100f, "攻擊力"); serializedObject.ApplyModifiedProperties(); } private void ProgressBar(float value, string label) { Rect rect = GUILayoutUtility.GetRect(18, 18); EditorGUI.ProgressBar(rect, value, label); EditorGUILayout.Space(); } }
這種方法和第一種方法效果是一樣的,就不上圖了。
擴展自定義組件我們除了寫編輯器類以外,還會用到很多特性,特性的使用在下一節。