I’m new to C# and I need some help with this.
In a script, I need a public array of float values and I want the inspector to create sliders for them. So this is what I wrote:
[Range (-1f, 1f)]
public float targetWeight;
It’s working as it should. The problem is, I want to know when the values have been changed. Afaik, using a “setter” is the way to go here. So I tried this:
[Range (-1f, 1f)]
public float targetWeight { set { OnValueChanged (); } get{ return targetWeight;} }
But then I get a compiler error “Range attribute is only valid on field declarations”. Help please?
First of all, the property you have made wouldn’t work, i.e. nothing will be stored in the array because you need to have a backing field to make properties work this way. Second, properties don’t show in the inspector. Third is just what the error says. You can’t have the Range attribute on a property because it won’t come up in the Inspector!
If you want to know when the values
have been changed during gameplay,
just do something like this:
[SerializeField]
private float[] mTargetWeight;
public float[] targetWeight {
get {
return mTargetWeight;
}
set {
mTargetWeight = value;
OnValueChanged();
}
}
and access the array in scripts using
the targetWeight property. If not, read on!
One solution (actually the only solution) to your problem can be to make a Custom Editor for your script. You can know more about how to do that here and here. In the OnInspectorGUI() method, you can do something like this to check whether the value has changed or not:
//MyScript is your script's class name
var myTarget = target as MyScript;
foreach(var f in myTarget.targetWeight) {
var prev = f;
f = EditorGUILayout.Slider(f, -1, 1);
if(prev != f) OnValueChanged();
}