Unity Version: 2019.4.26f1
I tried to create a ListView and setting the bindingPath to a serializedObject’s array property (In this case, an Array of Components), the code below for this is here
public class MyComponent : MonoBehaviour
{
string customName;
}
public class Data : ScriptableObject
{
[SerializeField]
private MyComponent[] myComponents;
}
[CustomEditor(typeof(Data))]
public class DataEditor : Editor
{
public override VisualElement CreateInspectorGUI() => CreateListView();
private ListView CreateListView()
{
ListView stateMachinesView = new ListView();
stateMachinesView.itemHeight = (int)(EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing);
stateMachinesView.makeItem = CreateField;
stateMachinesView.bindItem = BindField;
stateMachinesView.bindingPath = "myComponents";
stateMachinesView.style.height = 100;
stateMachinesView.Bind(serializedObject);
VisualElement CreateField() => new ObjectField();
void BindField(VisualElement arg1, int arg2)
{
SerializedProperty prop = stateMachines.FindPropertyRelative($"Array.data[{arg2}]");
ObjectField field = arg1 as ObjectField;
field.objectType = typeof(MyComponent);
field.bindingPath = prop.propertyPath;
if (prop != null && prop.objectReferenceValue)
{
MyCompponent myComp = prop.objectReferenceValue as MyComponent;
field.label = myComp.customName;
}
else
{
field.label = $"Element {arg2}";
}
field.BindProperty(serializedObject);
}
return stateMachinesView;
}
}
While this produces a somewhat proper list view, scrolling down to the bottom throws a nullReferenceException when the objectField’s bindingPath is set to the serializedProperty’s binding path, this is because the serializedProperty itself is null. which mainly meant that the FindPropertyRelative call is returning null on a specific index.
After doing some debugging by logging “arg2”, i discovered that the Listview would attempt to access [serializedProperty.arraySize + 1] elements from the source, this is an issue, as seen in the image below
(Notice how the array size is set to 9, but there are a total of 10 messages in the console instead of just 9)
Is there anything that can be done to fix this issue? When the ListView tries to display the broken element it “Mimicks” another element from the list, (Image above shows the broken element, which is after “Element 8” and the label has it as “Element 2”) it trying to simply hide the ListView from the inspector by setting the display to none doesnt work and causes more problems (Elements missing entirely, shown below)
