Skip to content

Instantly share code, notes, and snippets.

@sebtoun
Created October 13, 2021 19:04
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebtoun/a39ff98e36da753da97f87a594174ee1 to your computer and use it in GitHub Desktop.
Save sebtoun/a39ff98e36da753da97f87a594174ee1 to your computer and use it in GitHub Desktop.
Unity AnimationCurve decorator to clamp the curve like RangeAttribute is for float.
using UnityEngine;
public class ClampedCurveAttribute : PropertyAttribute
{
public readonly float MinX;
public readonly float MaxX;
public readonly float MinY;
public readonly float MaxY;
public ClampedCurveAttribute( float minX, float maxX, float minY, float maxY )
{
MinX = minX;
MaxX = maxX;
MinY = minY;
MaxY = maxY;
}
public ClampedCurveAttribute() : this( 0, 1, 0, 1 )
{
}
}
using UnityEditor;
using UnityEngine;
[ CustomPropertyDrawer( typeof( ClampedCurveAttribute ) ) ]
public class ClampedCurveDrawer : PropertyDrawer
{
public override void OnGUI( Rect position, SerializedProperty property, GUIContent label )
{
EditorGUI.BeginChangeCheck();
EditorGUI.PropertyField( position, property, label );
if ( EditorGUI.EndChangeCheck() )
{
var attr = (ClampedCurveAttribute) attribute;
var curve = property.animationCurveValue;
ClampCurve( curve, attr.MinX, attr.MaxX, attr.MinY, attr.MaxY );
property.animationCurveValue = curve;
}
}
public static void ClampCurve( AnimationCurve curve, float minX, float maxX, float minY, float maxY )
{
var keys = curve.keys;
for ( int i = 0; i < keys.Length; i++ )
{
keys[ i ].time = Mathf.Clamp( keys[ i ].time, minX, maxX );
keys[ i ].value = Mathf.Clamp( keys[ i ].value, minY, maxY );
}
keys[ 0 ].time = minX;
keys[ keys.Length - 1 ].time = maxX;
curve.keys = keys;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment