官方文檔 PropertyDrawers
Unity編輯器拓展(一)
Unity編輯器拓展(二)
Unity編輯器拓展(三)
繪制屬性 Property Drawers
繪制屬性可用于腳本上的屬性缩滨,在 Inspector 窗口中自定義某些控件的外觀凳干,或者控制特定的可序列化類的外觀。
繪制屬性有兩種用途:1.為可序列化類的每個實例自定義 GUI。2.為腳本成員屬性自定義 GUI肄满。
為可序列化類的每個實例自定義 GUI
如果腳本中屬性是自定義類,在 Inspector 中是不會顯示的质涛,如果需要顯示稠歉,我們可用 Serializable 修飾。
示例1:
using System; // for Serializable
public enum IngredientUnit { Spoon, Cup, Bowl, Piece }
[Serializable]
public class Ingredient {
public string name;
public int amount = 1;
public IngredientUnit unit;
}
public class GameRecipe : MonoBehaviour {
public Ingredient potionResult;
public Ingredient[] potionIngredients;
}
正確顯示如下圖所示:
我們可以使用 CustomPropertyDrawer 來自定義我們需要的顯示效果汇陆。如示例2:
[CustomPropertyDrawer(typeof(Ingredient))]
public class IngredientDrawer : PropertyDrawer {
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
EditorGUI.BeginProperty(position, label, property); // 開始繪制屬性
var indent = EditorGUI.indentLevel; // 用來緩存修改之前的縮進值
EditorGUI.indentLevel = 0; // 修改縮進為 0怒炸,不縮進
// 獲取屬性前值 label, 就是顯示在此屬性前面的那個名稱 label
position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);
// 定義此屬性的子框體區(qū)域
var amountRect = new Rect(position.x, position.y, 30, position.height);
var unitRect = new Rect(position.x + 35, position.y, 50, position.height);
var nameRect = new Rect(position.x + 90, position.y, position.width - 90, position.height);
// 繪制子屬性:PropertyField參數(shù)依次是: 框體位置,對應屬性毡代,顯示的label
// 如果你要顯示一個label阅羹,第三個參數(shù): new GUIContent("xxx")
EditorGUI.PropertyField(amountRect, property.FindPropertyRelative("amount"), GUIContent.none);
EditorGUI.PropertyField(unitRect, property.FindPropertyRelative("unit"), GUIContent.none);
EditorGUI.PropertyField(nameRect, property.FindPropertyRelative("name"), GUIContent.none);
EditorGUI.indentLevel = indent; // 恢復縮進
EditorGUI.EndProperty(); // 完成繪制
}
}
顯示效果圖:
為腳本成員屬性自定義 GUI
使用 Property Attributes 來給腳本的成員屬性自定義GUI。你可以使用內(nèi)建的和自定義的教寂。
內(nèi)建屬性有:
- Range() 將一個值指定在一定的范圍內(nèi)捏鱼,在Inspector面板中為其添加滑塊
- Multiline() 為一個string指定多行
- Header() 為屬性添加屬性標題
- Tooltip() 為屬性添加提示語
- Space() 添加指定行距
- ContextMenu() 為腳本添加菜單到右上角工具按鈕
- TextArea() 添加TextArea
示例3:
public class GameRecipe : MonoBehaviour {
public Ingredient potionResult;
public Ingredient[] potionIngredients;
[Header("Nick")]
public string nickName;
[Multiline(3)]
public string description;
[Space(20)]
[Range(0f, 10f), Tooltip("this is weight")]
public float weight;
[TextArea]
public string information;
[ContextMenu("Show Infomation")]
void ShowInfo() {
Debug.Log(information);
}
}
效果如圖:
自定義 PropertyAttribute:1.派生 PropertyAttribute 并定義此類。2. 在使用 CustomPropertyDrawer 實現(xiàn)繪制酪耕。
這種實現(xiàn)和之前的示例2類似就不展示示例了导梆。