当前位置:   article > 正文

【Unity】用PropertyDrawer自定义Inspector面板显示外观_unity propertydrawer自定义serializereference

unity propertydrawer自定义serializereference

举栗如图,将数组以二维矩阵的方式显示到Inspector面板

 

  1. using UnityEngine;
  2. using UnityEditor;
  3. [System.Serializable]
  4. public class InspectorGrid
  5. {
  6. public int rows;
  7. public int columns;
  8. [SerializeField]
  9. bool[] enabledBools;
  10. }
  11. // ------
  12. //用PropertyDrawer自定义Inspector面板显示外观
  13. [CustomPropertyDrawer(typeof(InspectorGrid))]
  14. public class InspectorGridDrawer : PropertyDrawer
  15. {
  16. float gridWidth = 15f;
  17. float gridHeight = 15f;
  18. float gridSpace = 1f;
  19. int rows;
  20. int columns;
  21. //自定义面板显示
  22. public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
  23. {
  24. //position: 在Inspector面板的位置、大小
  25. //property: 待绘制的属性
  26. //label: 值的字段名
  27. //绘制一个SerializedProperty的属性字段
  28. EditorGUI.PropertyField(position, property, label, true);
  29. //获取属性信息
  30. SerializedProperty data = property.FindPropertyRelative("enabledBools");
  31. rows = property.FindPropertyRelative("rows").intValue;
  32. columns = property.FindPropertyRelative("columns").intValue;
  33. if (rows < 0)
  34. rows = 0;
  35. if (columns < 0)
  36. columns = 0;
  37. //指定数组大小
  38. data.arraySize = rows * columns;
  39. //自定义显示区域
  40. if (property.isExpanded)
  41. {
  42. int count = 0;
  43. float targetX;
  44. float targetY;
  45. //遍历
  46. for (int r = 0; r < rows; r++)
  47. {
  48. for (int c = 0; c < columns; c++)
  49. {
  50. //计算位置
  51. targetX = position.xMin + ((gridWidth + gridSpace) * (c + 1));
  52. targetY = 60 + position.yMin + (gridHeight + gridSpace) * (r + 1);
  53. //位置、大小
  54. Rect rect = new Rect(targetX, targetY, 15f * (EditorGUI.indentLevel + 1), gridHeight);
  55. //绘制属性值
  56. EditorGUI.PropertyField(rect, data.GetArrayElementAtIndex(count), GUIContent.none);
  57. count++;
  58. }
  59. }
  60. }
  61. }
  62. //自定义高度
  63. public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
  64. {
  65. //按照行数增加高度
  66. if (property.isExpanded)
  67. return EditorGUI.GetPropertyHeight(property) + 20 + (15 * (rows + 1));
  68. return EditorGUI.GetPropertyHeight(property);
  69. }
  70. }

// 测试,Inspector面板显示如上图

  1. using UnityEngine;
  2. public class Test : MonoBehaviour
  3. {
  4. [SerializeField] InspectorGrid grid;
  5. }

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号