So I am making a custom editor script. I need to display a list with it. The list is populated by a custom class I made that inherits from ScriptableObject. It shows up fine, it adds elements fine. However, when I remove the last element of the list it gives me a null reference and won’t remove it. I can avoid the error with a Try-Catch, but I would prefer not to do that and do it the right way.
Here is the code that crashes (on ‘SerializedObject sc’ line):
void ShowElement(int index)
{
EditorGUILayout.BeginHorizontal();
{
GUI.color = Color.red;
if(GUILayout.Button("X", GUILayout.Width(25f)))
{
RemoveElement(index);
}
GUI.color = Color.white;
//try {
SerializedObject sc = new SerializedObject(mObject.FindProperty(string.Format(mListData, index)).objectReferenceValue);
var elementName = sc.FindProperty(mSCLevel).stringValue;
EditorGUILayout.LabelField(elementName);
//} catch {}
}
EditorGUILayout.EndHorizontal();
}
Here is the code that removes:
void RemoveElement(int index)
{
for( int i = index; i < mElementsCount.intValue - 1; i++)
SetElement(i, GetElement(i + 1));
mElementsCount.intValue--;
SceneView.RepaintAll();
}
I’ve tried null checks on the SerializedProperty and its objectReferenceValue–but even then, it still makes it to that line and gives a null reference error. What can I do? As I said, a TryCatch works, but I’d like to avoid that if possible.
Thanks