- Home /
Is it possible to define a Range for a float in a System.Serializable class?
Admittedly C# is still something I'm learning the ins and outs of, hopefully this is possible.
Say we have a serializable class:
[System.Serializable]
class CustomFloatParameter : System.Object {
[Range(0f, 10f)]
public float value = 1f;
public float timesTwo { get { return value * 2; } }
}
And we define that in a MonoBehaviour
class SomeComponent : MonoBehaviour {
public CustomFloatParameter someProperty;
}
Is there a way I can set what 0f and 10f might be in the [Range] where the field is defined?
Complete stab in the dark which I do not expect to work:
[Range(5f, 20f)]
public CustomFloatParameter someProperty;
(Similar to this, is there a way I can set the default value (1f) as well?)
I've just noticed http://docs.unity3d.com/ScriptReference/PropertyAttribute.html
Is this the sort of thing I'm looking for?
http://docs.unity3d.com/ScriptReference/RangeAttribute-ctor.html
Looks like that will control the values available by slider in the inspector. That won't prevent the value being set outside that range in script (do those checks yourself).
That it would. I guess I'm after a custom RangeAtttribute/PropertyAttribute style feature
Better clarifying my sample above, maybe it would look like:
[System.Serializable]
class CustomFloatParameter : System.Object {
[Range(A, B)]
public float value = C;
public float timesTwo { get { return value * 2; } }
}
......
class SomeComponent : $$anonymous$$onoBehaviour {
[CustomFloat(0f, 10f, 2f)]
CustomFloatParameter myCustomFloat;
}
A would become 0f, B would become 10f, and C would become 2f;
Though, I guess from what I've ready about PropertyAttributes and PropertyDrawers today I wouldn't have to worry about the [Range(..)] in CustomFloatParameter, the custom drawer code would handle that appropriately.
Answer by idbrii · Feb 04, 2018 at 12:29 AM
This was kindof demonstrated with the RangedFloat in this Unite 2016 talk on Scriptable Object .
You create your own attribute that will look inside your object and set its range.
The code for that talk is on bitbucket. Looks like this is the relevant commit. Look at MinMaxRangeAttribute, RangedFloat, and RangedFloatDrawer. I think the real magic happens in RangedFloatDrawer.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Is this a good way to handle range? 1 Answer
How to make a dynamic list of a serializable variable? 1 Answer
pre generated static Object in C# 1 Answer