Skip to content

Instantly share code, notes, and snippets.

@beardordie
Created August 18, 2018 19:16
Show Gist options
  • Save beardordie/76f016d9235a896fdfd26ad6e78e690b to your computer and use it in GitHub Desktop.
Save beardordie/76f016d9235a896fdfd26ad6e78e690b to your computer and use it in GitHub Desktop.
RangedFloat type with Custom Editor
using System;
[Serializable]
public struct RangedFloat
{
public float minValue;
public float maxValue;
public RangedFloat(float minValue, float maxValue) //constructor
{
this.minValue = minValue;
this.maxValue = maxValue;
}
}
// Place the following in RangedFloatDrawer.cs in an Editor folder
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(RangedFloat), true)]
public class RangedFloatDrawer : 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("minValue");
SerializedProperty maxProp = property.FindPropertyRelative("maxValue");
float minValue = minProp.floatValue;
float maxValue = maxProp.floatValue;
float rangeMin = 0;
float rangeMax = 1;
MinMaxRangeAttribute[] ranges = (MinMaxRangeAttribute[])fieldInfo.GetCustomAttributes(typeof(MinMaxRangeAttribute), true);
if(ranges.Length>0)
{
rangeMin = ranges[0].Min;
rangeMax = ranges[0].Max;
}
var minLabelRect = new Rect(position);
minLabelRect.width = 40;
GUI.Label(minLabelRect, new GUIContent(minValue.ToString("F2")));
position.xMin += 40;
var maxLabelRect = new Rect(position);
maxLabelRect.xMin = maxLabelRect.xMax - 40;
GUI.Label(maxLabelRect, new GUIContent(maxValue.ToString("F2")));
position.xMax -= 40;
EditorGUI.BeginChangeCheck();
EditorGUI.MinMaxSlider(position, ref minValue, ref maxValue, rangeMin, rangeMax);
if(EditorGUI.EndChangeCheck())
{
minProp.floatValue = minValue;
maxProp.floatValue = maxValue;
}
EditorGUI.EndProperty();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment