前言
對於Unity編輯器的擴展方法眾多,擴展對象包括Inspector頁面及頂部菜單欄。定制方法有兩種:
- Attributes屬性進行定制
- 繼承Editor類,重寫OnInspectorGUI()進行定制
項目地址:UnityEditor - SouthBegonia
Attributes屬性進行定制
該部分的擴展方法集中在Inspector中腳本面板,使用了Unity中的 Attributes 屬性 ,使得腳本在Inspector面板中規范化、便捷化。
[Header] 屬性標題
為后續區域代碼擬訂一個標題,用於區分和概述該區域代碼含義
[Header("武器")]
public int weapon;
public int ammunition;
public int aurability;
[Tooltip] 屬性提示
實現在Inspector中,鼠標位於該變量名字上時,提示該變量的描述信息
[Tooltip("玩家的名字,肯定不再是JOJO對吧")]
public string playerName;
[Space] 空行屬性
在Inspector腳本頁面創建空行以隔開上下可視參數
[Space]
public int health = 100;
[Range()] 范圍值屬性
使得變量的值僅可在該范圍內修改,並且可以在Inspector頁面呈現滑動修改變量的效果
[Range(0, 1000)]
public int exp = 0;
[Foldout] 屬性折疊
使得多個的變量在Inspector頁面實現集合、可折疊效果。(注:本方法並非Unity自帶,而是源自項目InspectorFoldoutGroup - PixeyeHQ,如需使用該方法,僅需要將項目的腳本配置到自身unity項目下即可)
[Pixeye.Unity.Foldout("Enemys")]
public GameObject a, b, c, d, e;
[SerializeField] 強制序列化
使得private變量在Inspector腳本頁面可見,同時也稱為強制序列化
[SerializeField]
private int coins;
[HideInInspector] 隱藏屬性
使得public變量在Inspector頁面不可視,進而實現保護變量
[HideInInspector]
public int maxHealth = 100;
[TextArea] 輸入域
對於字數較長的字符串,擴展其在Inspector中的編輯區大小(原本僅能單行,且無法自動換行)
[TextArea]
public string gameDescribe = "";
[AddComponentMenu] 添加組件到菜單
寫於類名前,可以將該類直接添加到Add Component菜單中
[AddComponentMenu("Managers/demo1")]
public class demo1 : MonoBehaviour
{
// ...
}
OnValidate() 數據檢查
對編輯狀態下、Inspector中輸入的數據進行檢查的函數
private void OnValidate()
{
if (health < 0)
{
Debug.LogError("生命值不可為負");
health = 0;
}
else if (health > 100)
{
Debug.LogError("生命值不可超過最大值 " + maxHealth);
health = 100;
}
}
[ContextMenu] 上下文菜單
可以為類增加一個上下文彈出菜單,在Inspector頁面對當前腳本右鍵(或者單擊腳本圖標右側三個豎點)即可彈出自定義的上下文菜單
[ContextMenu("顯示當前生命值")]
public void PrintHealth()
{
Debug.Log("Health = " + health);
}
[ContextMenuItem] 字段上下文菜單
區別於上面的ContextMenu
是在腳本名字處右鍵打開上下文菜單,該方法適用於在某一字段名字上右鍵打開上下文菜單:參數類型string,前name,后function
[ContextMenuItem("ResetHealth", "ResetHealth")]
public int health = 100;
public void ResetHealth()
{
health = maxHealth;
}
重寫OnInspectorGUI()進行定制
除了於上文運用Attributes屬性對腳本欄進行定制,也可以將腳本 繼承自Editor類,並重寫 OnInspectorGUI(),從而實現在Inspector頁面進行GUI繪制。大部分方法可以使用EditorGUILayout
類,或是GUILayout
類,與GUI在Scene中繪制的原理大致相同。
補充:
GUILayout.BeginHorizontal();
GUILayout.EndHorizontal();
// 等價於
using(new EditorGUILayout.HorizontalScope()) { }
完整代碼:PlayerInspector.cs
菜單欄的擴展
[MenuItem] 菜單欄
在編輯狀態可點擊上方自定義的菜單欄項實現特定功能,即擴展菜單欄項
[MenuItem("調試/查看版本信息")]
static void PrintSomething()
{
// 注意:僅有靜態函數才可使用該屬性
Debug.Log("當前Unity版本:" + Application.unityVersion);
}
三種重載方法:
public MenuItem(string itemName);
public MenuItem(string itemName, bool isValidateFunction); //不要把isValidateFunction設為true
public MenuItem(string itemName, bool isValidateFunction, int priority); //priority為該項在菜單欄中顯示順序
總述
兩種方法皆是對Inspector腳本頁面進行定制的方法:Attributes是官方提供的定制屬性類,簡單便捷五臟俱全;而對Editor類的繼承重寫則具有多的可擴展性,也相對較麻煩,此外繼承重寫Editor的方法不能與Attributes屬性共存,所以在進行各種的定制前請慎重選擇定制的方法。