Skip to content

Commit

Permalink
RangedInt type, with a possibility to use MinMaxRangeAttribute
Browse files Browse the repository at this point in the history
  • Loading branch information
Deadcows committed May 4, 2019
1 parent fd93a46 commit 7090dae
Showing 1 changed file with 57 additions and 2 deletions.
59 changes: 57 additions & 2 deletions Attributes/MinMaxRangeAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@

using System;
using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;

#endif

namespace MyBox
Expand All @@ -30,13 +30,68 @@ public struct RangedFloat
public float Min;
public float Max;
}

[Serializable]
public struct RangedInt
{
public int Min;
public int Max;
}
}

#if UNITY_EDITOR
namespace MyBox.Internal
{
[CustomPropertyDrawer(typeof(RangedInt), true)]
public class MinMaxRangeIntAttributeDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
label = EditorGUI.BeginProperty(position, label, property);
position = EditorGUI.PrefixLabel(position, label);

SerializedProperty minProp = property.FindPropertyRelative("Min");
SerializedProperty maxProp = property.FindPropertyRelative("Max");

float minValue = minProp.intValue;
float maxValue = maxProp.intValue;

float rangeMin = 0;
float rangeMax = 1;

var ranges = (MinMaxRangeAttribute[]) fieldInfo.GetCustomAttributes(typeof(MinMaxRangeAttribute), true);
if (ranges.Length > 0)
{
rangeMin = ranges[0].Min;
rangeMax = ranges[0].Max;
}

const float rangeBoundsLabelWidth = 40f;

var rangeBoundsLabel1Rect = new Rect(position);
rangeBoundsLabel1Rect.width = rangeBoundsLabelWidth;
GUI.Label(rangeBoundsLabel1Rect, new GUIContent(minValue.ToString("F2")));
position.xMin += rangeBoundsLabelWidth;

var rangeBoundsLabel2Rect = new Rect(position);
rangeBoundsLabel2Rect.xMin = rangeBoundsLabel2Rect.xMax - rangeBoundsLabelWidth;
GUI.Label(rangeBoundsLabel2Rect, new GUIContent(maxValue.ToString("F2")));
position.xMax -= rangeBoundsLabelWidth;

EditorGUI.BeginChangeCheck();
EditorGUI.MinMaxSlider(position, ref minValue, ref maxValue, rangeMin, rangeMax);
if (EditorGUI.EndChangeCheck())
{
minProp.intValue = Mathf.RoundToInt(minValue);
maxProp.intValue = Mathf.RoundToInt(maxValue);
}

EditorGUI.EndProperty();
}
}

[CustomPropertyDrawer(typeof(RangedFloat), true)]
public class MinMaxRangeAttributeDrawer : PropertyDrawer
public class MinMaxRangeFloatAttributeDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
Expand Down

0 comments on commit 7090dae

Please sign in to comment.