- Home /
Field creation order using (Editor)GUILayout creating odd behavior
So I'm writing a CustomEditor
for a class and running into an issue (actually 2, but I'm just focusing on the one here). It looks like GUILayout
(and EditorGUILayout
) seem to cache the value of the active field and it assumes that the fields will always be in the same order and reapplies that cached value to the field in the same spot, which is often the wrong field. Take the code below.
[CustomEditor(typeof(DebugRunner))]
public class DebugRunnerEditor : Editor
{
LinkedList<int> Fields = new LinkedList<int>();
int newField;
public override void OnInspectorGUI()
{
for(LinkedListNode<int> node = Fields.First;node != null;node = node.Next)
{
node.Value = EditorGUILayout.IntField("Field ", node.Value);
}
newField = EditorGUILayout.IntField("New Field", newField);
if (GUILayout.Button("Add"))
{
Fields.AddFirst(newField);
}
}
}
I've just created a quick mockup CustomEditor
for a debug class that I use to illustrate the problem. When the inspector first opens, it looks like figure A below. If I type 10 and click add, I get figure B. If you look closely, you can see the issue just start to show up already, but it's not very visible. Rather than my 'New Field' field being highlighted, the field I just added is highlighted. It looks like unity remembers that I'd previously selected the first field, and kept the first field selected even though the first field changed. If I add a 5 next I get figure C, which is where things really start to become problematic. When the script adds new elements, it adds them to the start of the list. So the first 5 is correct... but it looks like it replaced my 10 that I already had there with a 5 and if I'm not careful it will actually replace it. If I unselect the value without doing anything else, the 5 goes away and the 10 shows back up, at least most of the time. I did have at least one instance of the change being real, but was never able to replicate it while I was testing again.
What I'm actually doing is creating a custom editor for a class that includes a Dictionary<string,Stat>
member, where Stat is an abstract class that can be a CalculatedStat
(that uses a formula), a PureNumericStat
(which just contains a number), or a ModifiableStat
(which is designed to have a base value, which modifiers can be applied to). I use the CustomEditor
to add those objects to the dictionary, and it's moving values around depending on how many new fields show up when I add a new stat. How do I get the unity editor to react properly to new fields that are being added between calls to OnInspectorGUI
for a CustomEditor