用PropertyDrawer自定義Inspector面板顯示外觀
2019年02月13日 11:53:25 蕭_然 閱讀數:22更多
個人分類: 工具
版權聲明:歡迎大家留言討論共同進步,轉載請註明出處 https://blog.csdn.net/qq_39108767/article/details/87170224
舉慄如圖,將數組以二維矩陣的方式顯示到Inspector面板
-
using UnityEngine;
-
using UnityEditor;
-
[System.Serializable]
-
public class InspectorGrid
-
{
-
public int rows;
-
public int columns;
-
[SerializeField]
-
bool[] enabledBools;
-
}
-
// ------
-
//用PropertyDrawer自定義Inspector面板顯示外觀
-
[CustomPropertyDrawer(typeof(InspectorGrid))]
-
public class InspectorGridDrawer : PropertyDrawer
-
{
-
float gridWidth = 15f;
-
float gridHeight = 15f;
-
float gridSpace = 1f;
-
int rows;
-
int columns;
-
//自定義面板顯示
-
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
-
{
-
//position: 在Inspector面板的位置、大小
-
//property: 待繪製的屬性
-
//label: 值的字段名
-
//繪製一個SerializedProperty的屬性字段
-
EditorGUI.PropertyField(position, property, label, true);
-
//獲取屬性信息
-
SerializedProperty data = property.FindPropertyRelative("enabledBools");
-
rows = property.FindPropertyRelative("rows").intValue;
-
columns = property.FindPropertyRelative("columns").intValue;
-
if (rows < 0)
-
rows = 0;
-
if (columns < 0)
-
columns = 0;
-
//指定數組大小
-
data.arraySize = rows * columns;
-
//自定義顯示區域
-
if (property.isExpanded)
-
{
-
int count = 0;
-
float targetX;
-
float targetY;
-
//遍歷
-
for (int r = 0; r < rows; r++)
-
{
-
for (int c = 0; c < columns; c++)
-
{
-
//計算位置
-
targetX = position.xMin + ((gridWidth + gridSpace) * (c + 1));
-
targetY = 60 + position.yMin + (gridHeight + gridSpace) * (r + 1);
-
//位置、大小
-
Rect rect = new Rect(targetX, targetY, 15f * (EditorGUI.indentLevel + 1), gridHeight);
-
//繪製屬性值
-
EditorGUI.PropertyField(rect, data.GetArrayElementAtIndex(count), GUIContent.none);
-
count++;
-
}
-
}
-
}
-
}
-
//自定義高度
-
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
-
{
-
//按照行數增加高度
-
if (property.isExpanded)
-
return EditorGUI.GetPropertyHeight(property) + 20 + (15 * (rows + 1));
-
return EditorGUI.GetPropertyHeight(property);
-
}
-
}
// 測試,Inspector面板顯示如上圖
-
using UnityEngine;
-
public class Test : MonoBehaviour
-
{
-
[SerializeField] InspectorGrid grid;
-
}