Skip to content

Instantly share code, notes, and snippets.

@phosphoer
Created January 7, 2025 00:51
Show Gist options
  • Save phosphoer/565d78b3c6b55a4954ea97bc01e38bb4 to your computer and use it in GitHub Desktop.
Save phosphoer/565d78b3c6b55a4954ea97bc01e38bb4 to your computer and use it in GitHub Desktop.
Ranged Float Unity
using UnityEngine;
[System.Serializable]
public struct RangedFloat
{
public float MinValue;
public float MaxValue;
public float RangeSize => MaxValue - MinValue;
public float RandomValue
{
get { return Random.Range(MinValue, MaxValue); }
}
public RangedFloat(float min = 0, float max = 0)
{
MinValue = min;
MaxValue = max;
}
public bool InRange(float value, bool inclusive = true)
{
if (inclusive)
{
return value >= MinValue && value <= MaxValue;
}
return value > MinValue && value < MaxValue;
}
public float Clamp(float value)
{
return Mathf.Clamp(value, MinValue, MaxValue);
}
public float Lerp(float t)
{
return Mathf.Lerp(MinValue, MaxValue, t);
}
public float LerpUnclamped(float t)
{
return Mathf.LerpUnclamped(MinValue, MaxValue, t);
}
public float InverseLerp(float value)
{
return Mathf.InverseLerp(MinValue, MaxValue, value);
}
public float SeededRandom(System.Random rand)
{
return rand.NextFloatRanged(MinValue, MaxValue);
}
}
using UnityEngine;
using UnityEditor;
[CustomPropertyDrawer(typeof(RangedFloat))]
[CustomPropertyDrawer(typeof(RangedInt))]
public class RangedFloatPropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
SerializedProperty minProp = property.FindPropertyRelative("MinValue");
SerializedProperty maxProp = property.FindPropertyRelative("MaxValue");
position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);
Rect drawRect = position;
bool drawLabels = position.width > 200;
int oldIndentLevel = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
GUIStyle labelStyle = new GUIStyle(GUI.skin.label);
if (drawLabels)
{
float minWidth, maxWidth = 0;
labelStyle.CalcMinMaxWidth(new GUIContent("Min"), out minWidth, out maxWidth);
drawRect.width = minWidth;
EditorGUI.LabelField(drawRect, "Min", labelStyle);
drawRect.x += drawRect.width + 5;
}
drawRect.width = 50;
EditorGUI.PropertyField(drawRect, minProp, GUIContent.none);
drawRect.x += drawRect.width + 10;
if (drawLabels)
{
float minWidth, maxWidth = 0;
labelStyle.CalcMinMaxWidth(new GUIContent("Max"), out minWidth, out maxWidth);
drawRect.width = minWidth;
EditorGUI.LabelField(drawRect, "Max", labelStyle);
drawRect.x += drawRect.width + 5;
}
drawRect.width = 50;
EditorGUI.PropertyField(drawRect, maxProp, GUIContent.none);
EditorGUI.indentLevel = oldIndentLevel;
EditorGUI.EndProperty();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment