GameObjectChanceTableDrawer.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using UnityEditor;
  4. using UnityEditorInternal;
  5. using UnityEngine;
  6. namespace DunGen.Editor.Drawers
  7. {
  8. [CustomPropertyDrawer(typeof(GameObjectChanceTable))]
  9. sealed class GameObjectChanceTableDrawer : PropertyDrawer
  10. {
  11. private readonly Dictionary<string, ReorderableList> lists = new Dictionary<string, ReorderableList>();
  12. private ReorderableList GetOrCreateList(SerializedProperty property, GUIContent label)
  13. {
  14. ReorderableList list = null;
  15. if (lists.TryGetValue(property.propertyPath, out list))
  16. return list;
  17. else
  18. {
  19. var weightsProperty = property.FindPropertyRelative("Weights");
  20. var targetObject = property.serializedObject.targetObject;
  21. var chanceTable = (GameObjectChanceTable)fieldInfo.GetValue(targetObject);
  22. list = new ReorderableList(property.serializedObject, weightsProperty, true, true, true, true)
  23. {
  24. drawElementCallback = (rect, index, isActive, isFocused) => EditorGUI.PropertyField(rect, weightsProperty.GetArrayElementAtIndex(index), GUIContent.none),
  25. drawHeaderCallback = (rect) => EditorGUI.LabelField(rect, label.text + " (" + weightsProperty.arraySize + ")"),
  26. elementHeightCallback = (index) => EditorGUI.GetPropertyHeight(weightsProperty.GetArrayElementAtIndex(index)),
  27. onAddCallback = (l) =>
  28. {
  29. Undo.RecordObject(targetObject, "Add GameObject Chance");
  30. chanceTable.Weights.Add(new GameObjectChance());
  31. Undo.FlushUndoRecordObjects();
  32. },
  33. };
  34. lists[property.propertyPath] = list;
  35. return list;
  36. }
  37. }
  38. public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
  39. {
  40. var list = GetOrCreateList(property, label);
  41. return list.GetHeight();
  42. }
  43. public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
  44. {
  45. var list = GetOrCreateList(property, label);
  46. var attribute = fieldInfo.GetCustomAttributes(typeof(AcceptGameObjectTypesAttribute), true)
  47. .Cast<AcceptGameObjectTypesAttribute>()
  48. .FirstOrDefault();
  49. if (attribute != null)
  50. GameObjectChanceDrawer.FilterOverride = attribute.Filter;
  51. EditorGUI.BeginProperty(position, label, property);
  52. list.DoList(position);
  53. EditorGUI.EndProperty();
  54. if(attribute != null)
  55. GameObjectChanceDrawer.FilterOverride = null;
  56. }
  57. }
  58. }