Script A is a controller that holds a declaration for a float with a range:
[Range(0, 135f)]
public float RotatingPart;
Script B initialises a UI Slider to control RotatingPart and handles the OnValueChanged. This is working.
However, I can’t figure out how to automatically set the range of the Slider to match the Float’s range. Is there a way to read this value?
i would assume its not possible to get at runtime, since the range is only used by the editor it does not even exist in the SerializedObject. If i needed that data at runtime, i would make my own struct type that stores the min, max and value.
You say that, but from what I can tell the Attributes aren’t surrounded by #if UNITY_EDITOR pre-processors, nor are they using the System.Diagnostics.Conditional attribute to conditionally compile them and they’re in the regular UnityEngine assembly.
You’d have to test, but they might actually get built into the game from what I can see.
they might, but would require reflection to access, yeah looked at the code, pretty sure you can get them with reflection if wanted just like you would one of your own custom attributes.
i can give a better example once i get to my work computer, but once you got your field, property or method, you can call GetCustomAttribute on it passing RangeAttribute for T.
keep in mind reflection is pretty slow, so i would get it once and cache the information.
I see your point. To provide some background: these GO’s containing script A are delivered and maintained by a third party. Hence we prefer not to edit these scripts. We could however ask them to store the min/max values in separate variables from now on.
Reflection is the only way to access attributes at runtime as they are pure metadata. I also wouldn’t recommend to use such attributes for storing class relevant data. As spiney suggested, just use a constant like this:
public const float RotatingPartMax = 135f;
[Range(0, RotatingPartMax)]
public float RotatingPart;
Now you can simply use that constant wherever you need it inside your code.