Files
2026-02-21 16:45:37 +08:00

93 lines
1.2 KiB
C#

using System;
using UnityEngine;
namespace BitStrap
{
[Serializable]
public class NumberBounds<T> : IValidatable where T : IComparable<T>
{
[SerializeField]
protected T min = default(T);
[SerializeField]
protected T max = default(T);
public T Min
{
get
{
return min;
}
set
{
min = value;
ValidateBounds();
}
}
public T Max
{
get
{
return max;
}
set
{
max = value;
ValidateBounds();
}
}
public NumberBounds()
{
}
public NumberBounds(T min, T max)
{
Set(min, max);
}
public void Set(T min, T max)
{
this.min = min;
this.max = max;
ValidateBounds();
}
public T Clamp(T value)
{
value = GetMax(value, min);
value = GetMin(value, max);
return value;
}
public T SelectMax(bool selectMax)
{
return (!selectMax) ? min : max;
}
void IValidatable.Validate()
{
ValidateBounds();
}
protected static T GetMin(T a, T b)
{
return (a.CompareTo(b) > 0) ? b : a;
}
protected static T GetMax(T a, T b)
{
return (a.CompareTo(b) < 0) ? b : a;
}
private void ValidateBounds()
{
T a = min;
T b = max;
min = GetMin(a, b);
max = GetMax(a, b);
}
}
}