Skip to content

Instantly share code, notes, and snippets.

@gfsl
Created August 3, 2013 06:20
Show Gist options
  • Save gfsl/6145429 to your computer and use it in GitHub Desktop.
Save gfsl/6145429 to your computer and use it in GitHub Desktop.
[DynamicRange] Like [Range], but pulls Min and Max from introspected VarName_min and VarName_max variables. Floats and Ints. Attribute in \Attributes, Drawer in \Editor.
using UnityEngine;
using UnityEditor;
public class DynamicRangeAttribute : PropertyAttribute {
public DynamicRangeAttribute() { }
public float GetMin(SerializedProperty prop){
var minProp = prop.serializedObject.FindProperty(prop.name + "_min");
if(minProp == null){
Debug.LogWarning(prop.name + "_min not found.");
return 0.0f;
}
return ValueForProperty(minProp);
}
public float GetMax(SerializedProperty prop){
var maxProp = prop.serializedObject.FindProperty(prop.name + "_max");
if(maxProp == null){
Debug.LogWarning(prop.name + "_max not found.");
return 0.0f;
}
return ValueForProperty(maxProp);
}
private float ValueForProperty(SerializedProperty prop){
switch(prop.propertyType){
case SerializedPropertyType.Integer:
return prop.intValue;
case SerializedPropertyType.Float:
return prop.floatValue;
default:
return 0.0f;
}
}
}
using UnityEngine;
using UnityEditor;
[CustomPropertyDrawer(typeof(DynamicRangeAttribute))]
public class DynamicRangeDrawer : PropertyDrawer {
public override void OnGUI (Rect position, SerializedProperty prop, GUIContent label) {
var reflectedAttribute = attribute as DynamicRangeAttribute;
if (prop.propertyType == SerializedPropertyType.Float)
EditorGUI.Slider(position, prop, reflectedAttribute.GetMin(prop), reflectedAttribute.GetMax(prop), label);
else if(prop.propertyType == SerializedPropertyType.Integer)
EditorGUI.IntSlider(position, prop, (int)reflectedAttribute.GetMin(prop), (int)reflectedAttribute.GetMax(prop), label);
else
EditorGUI.HelpBox(position, "DynamicRangeDrawer can only be used on Floats and Ints.", MessageType.Error);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment