Skip to content

Instantly share code, notes, and snippets.

@timrodz
Forked from LotteMakesStuff/MinMaxAttribute.cs
Created November 29, 2017 01:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timrodz/9f59a7379849b249d98f222d032f4238 to your computer and use it in GitHub Desktop.
Save timrodz/9f59a7379849b249d98f222d032f4238 to your computer and use it in GitHub Desktop.
MinMax property drawer for Unity - Add a [MinMax] attribute to a property to draw a useful min/max setting slider.
// NOTE DONT put in an editor folder
using UnityEngine;
public class MinMaxAttribute : PropertyAttribute
{
public float MinLimit = 0;
public float MaxLimit = 1;
public MinMaxAttribute(int min, int max)
{
MinLimit = min;
MaxLimit = max;
}
}
// NOTE put in a Editor folder
using UnityEngine;
using UnityEditor;
[CustomPropertyDrawer(typeof(MinMaxAttribute))]
public class MinMaxDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
MinMaxAttribute minMax = attribute as MinMaxAttribute;
if (property.propertyType == SerializedPropertyType.Vector2)
{
float minValue = property.vector2Value.x;
float maxValue = property.vector2Value.y;
float minLimit = 0;
float maxLimit = 1;
EditorGUI.MinMaxSlider(position, label, ref minValue, ref maxValue, minLimit, maxLimit);
var vec = Vector2.zero;
vec.x = minValue;
vec.y = maxValue;
property.vector2Value = vec;
}
}
}
// This componnet Demos how to use MinMax attribute! Uses the ReadOnly attribute found here https://gist.github.com/LotteMakesStuff/c0a3b404524be57574ffa5f8270268ea
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class VolumeRandomizer : MonoBehaviour {
public AudioSource source;
public float Size;
[MinMax(0,1)]
public Vector2 VolumeRange = new Vector2(0, 1);
[ReadOnly]
public Vector2 RawMinMaxVolumes;
[ReadOnly]
public float valueRange;
// Use this for initialization
void Start () {
}
// Update is called once per frame
[ExecuteInEditMode]
void Update () {
valueRange = VolumeRange.y - VolumeRange.x;
RawMinMaxVolumes = VolumeRange;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment