用PropertyDrawer自定义Inspector面板显示外观

用PropertyDrawer自定义Inspector面板显示外观

2019年02月13日 11:53:25 萧_然 阅读数:22更多

个人分类: 工具

版权声明:欢迎大家留言讨论共同进步,转载请注明出处 https://blog.csdn.net/qq_39108767/article/details/87170224

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

 
  1. using UnityEngine;

  2. using UnityEditor;

  3.  
  4. [System.Serializable]

  5. public class InspectorGrid

  6. {

  7. public int rows;

    扫描二维码关注公众号,回复: 5695740 查看本文章
  8. public int columns;

  9.  
  10. [SerializeField]

  11. bool[] enabledBools;

  12. }

  13.  
  14. // ------

  15.  
  16. //用PropertyDrawer自定义Inspector面板显示外观

  17. [CustomPropertyDrawer(typeof(InspectorGrid))]

  18. public class InspectorGridDrawer : PropertyDrawer

  19. {

  20. float gridWidth = 15f;

  21. float gridHeight = 15f;

  22. float gridSpace = 1f;

  23.  
  24. int rows;

  25. int columns;

  26.  
  27. //自定义面板显示

  28. public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)

  29. {

  30. //position: 在Inspector面板的位置、大小

  31. //property: 待绘制的属性

  32. //label: 值的字段名

  33.  
  34. //绘制一个SerializedProperty的属性字段

  35. EditorGUI.PropertyField(position, property, label, true);

  36.  
  37. //获取属性信息

  38. SerializedProperty data = property.FindPropertyRelative("enabledBools");

  39. rows = property.FindPropertyRelative("rows").intValue;

  40. columns = property.FindPropertyRelative("columns").intValue;

  41.  
  42. if (rows < 0)

  43. rows = 0;

  44.  
  45. if (columns < 0)

  46. columns = 0;

  47.  
  48. //指定数组大小

  49. data.arraySize = rows * columns;

  50.  
  51. //自定义显示区域

  52. if (property.isExpanded)

  53. {

  54. int count = 0;

  55. float targetX;

  56. float targetY;

  57.  
  58. //遍历

  59. for (int r = 0; r < rows; r++)

  60. {

  61. for (int c = 0; c < columns; c++)

  62. {

  63. //计算位置

  64. targetX = position.xMin + ((gridWidth + gridSpace) * (c + 1));

  65. targetY = 60 + position.yMin + (gridHeight + gridSpace) * (r + 1);

  66. //位置、大小

  67. Rect rect = new Rect(targetX, targetY, 15f * (EditorGUI.indentLevel + 1), gridHeight);

  68. //绘制属性值

  69. EditorGUI.PropertyField(rect, data.GetArrayElementAtIndex(count), GUIContent.none);

  70.  
  71. count++;

  72. }

  73. }

  74. }

  75. }

  76.  
  77. //自定义高度

  78. public override float GetPropertyHeight(SerializedProperty property, GUIContent label)

  79. {

  80. //按照行数增加高度

  81. if (property.isExpanded)

  82. return EditorGUI.GetPropertyHeight(property) + 20 + (15 * (rows + 1));

  83.  
  84. return EditorGUI.GetPropertyHeight(property);

  85. }

  86.  
  87. }

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

 
  1. using UnityEngine;

  2.  
  3. public class Test : MonoBehaviour

  4. {

  5. [SerializeField] InspectorGrid grid;

  6.  
  7. }

猜你喜欢

转载自blog.csdn.net/linuxheik/article/details/88870379
今日推荐