- Home /
Problem with variables and inspector
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?
Answer by EvilTak · Aug 30, 2015 at 10:07 AM
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();
}
Your answer
Follow this Question
Related Questions
View script variables within an array of scripts in Inspector 1 Answer
Array with multiple variables in Inspector 1 Answer
Why does new GUIStyle() give "object reference not set to an instance of an object" error? 1 Answer
Access to components and their variables in Array. 0 Answers
Array not updating in inspector 0 Answers