- Home /
How to use arrays with custom inspector code?
I seem to be stuck in a catch 22 situation with the OnInspectorGUI method of Unity's UnityEditor class. I want to name array elements in the inspector for easy editing, currently I'm using, as per the documentation / tutorial:
public override void OnInspectorGUI()
{
J_Character charScript = (J_Character)target;
charScript.aBaseStats[0] = EditorGUILayout.FloatField("Base Health", charScript.aBaseStats[0]);
}
In my J_Character class I initialise the aBaseStats array like so:
public float[] aBaseStats = new float[35];
...I've also tried in the Awake or Start functions:
void Awake(){
aBaseStats = new float[35];
}
The problem is that whenever I try to do anything in the editor (and thus OnInspectorGUI is called) I get an index out of range error pointing to the line
charScript.aBaseStats[0] = EditorGUILayout.FloatField("Base Health", charScript.aBaseStats[0]);
I'm guessing this is because my array is initialized on game start while the editor code is running all the time while developing.
How can I get round this situation?
Many thanks.
Answer by IsaiahKelly · May 18, 2016 at 05:41 PM
The problem is not with how you're initializing the array, but rather how your custom editor is trying to access the array. Getting arrays working in a custom editor is not so simple, especially if you want to name each element! Take a look at the catlike coding Custom List tutorial to see what I mean.
I want to name array elements in the inspector for easy editing
I have a feeling you're going about this wrong. If you want a hard set number of named stat fields, it's easiest to just create each one manually like so:
public float baseHealth = 1;
public float baseStrength = 1;
public float baseAgility = 1;
If you want a flexible amount of named stats it's easiest to do that like this:
[System.Serializable]
public class Stat
{
public string name;
public float value;
}
public Stat[] aBaseStats;
In this case Unity will automatically use the public string name field as the label of each element in the array that has one, instead of the default "Element X".
If you want to do anything more complicated then this, you're going to need to learn a lot more about custom editor programing and the tutorial linked above is a good place to start.