FloatRangeDrawer.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using UnityEditor;
  2. using UnityEngine;
  3. using System.Reflection;
  4. namespace DunGen.Editor.Drawers
  5. {
  6. [CustomPropertyDrawer(typeof(FloatRange))]
  7. sealed class FloatRangeDrawer : PropertyDrawer
  8. {
  9. public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
  10. {
  11. var minProperty = property.FindPropertyRelative("Min");
  12. var maxProperty = property.FindPropertyRelative("Max");
  13. EditorGUI.BeginProperty(position, label, property);
  14. // Get limits from attribute if present
  15. float minLimit = 0.0f;
  16. float maxLimit = 1.0f;
  17. if (fieldInfo != null)
  18. {
  19. var limitAtt = fieldInfo.GetCustomAttribute<FloatRangeLimitAttribute>();
  20. if (limitAtt != null)
  21. {
  22. minLimit = limitAtt.MinLimit;
  23. maxLimit = limitAtt.MaxLimit;
  24. }
  25. }
  26. // Get current values
  27. float minValue = minProperty.floatValue;
  28. float maxValue = maxProperty.floatValue;
  29. const float fieldWidth = 40f;
  30. const float spacing = 4f;
  31. Rect labelRect = new Rect(position.x, position.y, EditorGUIUtility.labelWidth, position.height);
  32. Rect minRect = new Rect(labelRect.xMax, position.y, fieldWidth, position.height);
  33. Rect sliderRect = new Rect(minRect.xMax + spacing, position.y, position.width - labelRect.width - fieldWidth * 2 - spacing * 2, position.height);
  34. Rect maxRect = new Rect(sliderRect.xMax + spacing, position.y, fieldWidth, position.height);
  35. EditorGUI.LabelField(labelRect, label);
  36. // Min float field
  37. minValue = EditorGUI.FloatField(minRect, minValue);
  38. minValue = Mathf.Clamp(minValue, minLimit, maxValue);
  39. // Max float field
  40. maxValue = EditorGUI.FloatField(maxRect, maxValue);
  41. maxValue = Mathf.Clamp(maxValue, minValue, maxLimit);
  42. // Slider
  43. EditorGUI.MinMaxSlider(sliderRect, ref minValue, ref maxValue, minLimit, maxLimit);
  44. minProperty.floatValue = minValue;
  45. maxProperty.floatValue = maxValue;
  46. EditorGUI.EndProperty();
  47. }
  48. }
  49. }