Null SerializedProperty SerializedObject upon Removal from list

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

1 Answer

1

That should be i < mElementsCount.intValue -2 I think.

that's not it, in fact that removes the last element if you click on the second to last element

So your SetElement/GetElement code uses a 1 based index?

In any case you can probably fix it like this: if(GUILayout.Button("X", GUILayout.Width(25f))) { RemoveElement(index); } else { 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); }

Yeah I can't see a < and a -1 as a count -2: I must be tired... Well that why I suggested the if - because the code I've put in the else is expecting there to be an entry still.

You can do an else there because the next frame it will be back.