赞
踩
举栗如图,将数组以二维矩阵的方式显示到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;
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。