Enumarting SerializedProperty throws an exception

Hi, why this code throws an exception?

SerializedProperty serializedProperty = serializedObject.GetIterator();

foreach (var item in serializedProperty)
{
     EditorGUILayout.PropertyField((SerializedProperty)item);
}

Here an exception info: Assertion failed: Invalid iteration - (You need to call Next (true) on the first element to get to the first element)

I need enumerate serializedProperty through foreach.

Hope on your help.

Thanks!

I have no idea about that, personally, but a quick google search showed me this:

It’s ‘for’ not ‘foreach’ but it definitely includes Next (true) 2 or 3 times , but Next(false) through the loop.
It’s a long answer, I figure it might help ya. :slight_smile:

The assertion explains what is happening: You need a single call to serializedProperty.Next(true) before you can start iterating in a foreach block.

SerializedProperty serializedProperty = serializedObject.GetIterator();
serializedProperty.Next(true); // this is the missing ingredient
foreach (var item in serializedProperty)
{
    EditorGUILayout.PropertyField((SerializedProperty)item);
}

That is a much (smaller) answer. Nice. :slight_smile:

I knew that was part of the answer, didn’t know it was all of it* …

Sorry for bumping this old one but what kru posted above did not work for me (Unity 2019.4LTS). The exception vanished but not iteration took place. I ended up using this code:

SerializedProperty serializedProperty = serializedObject.GetIterator();
while(serializedProperty.NextVisible(enterChildren: true))
{
   EditorGUILayout.PropertyField(serializedProperty);
}

Maybe it will help someone else who stumbles across this.