How to iterate over Serialized List?
Currently what I am doing this but it doesnt work, it prints the correct size of the serialized array but not the content, how can I do it?
Debug.Log("Size: " + l.serializedProperty.GetArrayElementAtIndex(l.index).FindPropertyRelative("down").arraySize);
for (int i = 0; i < l.serializedProperty.GetArrayElementAtIndex(l.index).FindPropertyRelative("down").arraySize; i++) {
Debug.Log(l.serializedProperty.GetArrayElementAtIndex(l.index).FindPropertyRelative("down").GetArrayElementAtIndex(i));
}
Answer by oscarAbraham · Jun 25, 2021 at 05:50 PM
It depends on what's inside "down". GetArrayElementAtIndex
just returns another SerializedProperty, so you need to access what's inside that SerializedProperty to print it. Suppose down
is a a List of GameObjects: public List<GameObject> down;
, you could do it like this:
SerializedProperty downProperty = l.serializedProperty.GetArrayElementAtIndex(l.index).FindPropertyRelative("down");
Debug.log(downProperty.arraySize);
for (int i = 0; i < downProperty.arraySize; i++;)
{
Debug.Log(downProperty.GetArrayElementAtIndex(i).objectReferenceValue);
}
You can find how to get the value of different types of properties in this doc page. All the members that have the word "value" in them serve to access different types of data. Although, if down
is an array of custom structs or classes, you'll need to do a bit more than that.
It is actually a List<GameObject>
, I am currently using objectReferance as GameObject
is it the best practice?
@kayraucklnc Yeah, it's perfectly fine; that's what everyone does. I modified the answer's example to make down
a list of GameObjects. Does it work for you?
EDIT: Well, it's not objectReference
; it's objectReferenceValue
.
Hi, Uhm. If it works for you, could you mark my answer as correct? If it doesn't, could you share some of the class being serialized? That would give me a better idea of what isn't working. Either way, I'd appreciate some feedback or resolution, as it helps other people finding this question in the future, and it helps me to measure the productiveness of my time.
It totally worked! Thank you, one more follow-up question, sometimes I cast with as GameObject
but since it is actually a null value It gives me an error what's the best way to avoid this? Should I use try-catch?
Your answer
Follow this Question
Related Questions
Custom Editors - Array of Custom Classes 2 Answers
[Simple question] Adding a new SerializedProperty to a SerializedObject 1 Answer
Unity5-serializedObject.FindProperty("listname") for ReorderableList doesn't work... 2 Answers
Applying values from an animationClip to bones of a skinnedMesh via code? 0 Answers
How is my waypoint line going back to the gameobject it is stored in and not to the waypoint 0 0 Answers