The [Units]
attribute and its children can be used on float
fields to give them a suffix indicating what kind of units they represent. This changes how it is displayed, but still allows you to enter values normally.
Examples
The Animancer.Units
namespace contains attributes for various common units:
using Animancer;
using Animancer.Units;
using UnityEngine;
public class UnitsExample : MonoBehaviour
{
[Header("Standard Units")]
[SerializeField, Degrees] private float _Angle;
[SerializeField, DegreesPerSecond] private float _RotationSpeed;
[SerializeField, Meters] private float _Distance;
[SerializeField, MetersPerSecond] private float _Speed;
[SerializeField, MetersPerSecondPerSecond] private float _Acceleration;
[SerializeField, Multiplier] private float _Multiplier;
[SerializeField, Seconds] private float _Duration;
You can also use the [Units]
attribute directly:
[Header("Custom Units")]
[SerializeField, Units(" kg")] private float _Weight;
Or make your own attributes so you don't need to repeat the suffix string on every field that uses it:
public class KilometersAttribute : UnitsAttribute
{
public KilometersAttribute() : base(" km") { }
}
[SerializeField, Kilometers] private float _Length;
Multi Fields
You can specify multiple units and their conversion ratios:
public class MetersAndCentimetersAttribute : UnitsAttribute
{
public MetersAndCentimetersAttribute()
: base(new float[] { 1, 100 }, new string[] { " m", " cm" }) { }
}
[SerializeField, MetersAndCentimeters] private float _Width;
Defaults
Middle Clicking on a field will reset its value to 0
, but you can give it a [DefaultValue]
attribute to set a custom value as the default and optionally a secondary default value which is used if you reset the value when it was already at the primary default:
[SerializeField, Seconds, DefaultValue(0.25f, 0f)] private float _FadeDuration = 0.25f;
Rules
You can also specify a Validate.Value
rule to limit the allowed values:
[SerializeField, Meters(Rule = Validate.Value.IsNotNegative)] private float _Radius;