Skip to content

Instantly share code, notes, and snippets.

@kraj0t
Last active March 13, 2024 10:21
Show Gist options
  • Save kraj0t/0afac3163a73d987bef4eb9e21f56d92 to your computer and use it in GitHub Desktop.
Save kraj0t/0afac3163a73d987bef4eb9e21f56d92 to your computer and use it in GitHub Desktop.
Clamped AnimationCurve GUI - constrains the curve to a range, typically 0-1
using System;
using UnityEngine;
/// <summary>Constrains an AnimationCurve to a specific range. Use the default constructor for the typical 0-1 range. Use Mathf.Infinity to unconstrain specific values.</summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class ClampedCurveAttribute : PropertyAttribute
{
public Rect ranges;
public ClampedCurveAttribute()
{
ranges = new Rect(0, 0, 1, 1);
}
public ClampedCurveAttribute(float minX, float minY,float maxX, float maxY)
{
ranges = new Rect(minX, minY, maxX - minX, maxY - minY);
}
}
using UnityEngine;
using UnityEditor;
[CustomPropertyDrawer(typeof(ClampedCurveAttribute))]
public class ClampedCurveDrawer : PropertyDrawer
{
private const float ClampToggleWidth = 60;
private bool showClamped = true;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
ClampedCurveAttribute attr = attribute as ClampedCurveAttribute;
if (property.propertyType == SerializedPropertyType.AnimationCurve)
{
var curveRect = new Rect(position.x, position.y, position.width - ClampToggleWidth, position.height);
var toggleRect = new Rect(curveRect.xMax, position.y, ClampToggleWidth, position.height);
if (showClamped)
{
EditorGUI.CurveField(curveRect, property, Color.cyan, attr!.ranges, label);
}
else
{
EditorGUI.PropertyField(curveRect, property, label);
}
EditorGUIUtility.labelWidth = 40;
showClamped = EditorGUI.Toggle(toggleRect, "Clamp", showClamped);
}
else
{
Debug.LogError("ClampedCurveAttribute must only be used on AnimationCurve fields.", property.serializedObject.targetObject);
EditorGUI.PropertyField(position, property, label);
}
}
}
// ...
[SerializeField, ClampedCurve(0, 0, 1, 1)]
private AnimationCurve curve = AnimationCurve.Linear(0, 0, 1, 1);
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment