Creative Magic
Creative Magic

Reputation: 3141

How to convert List<T> to an Object

In Unity I've decided to make a custom editor for my component.
The component itself has a list of objects that I've declared as List.

The Editor targets this like this:

myCustomList = serializedObject.FindProperty ("myCustomList");

The problem is that when I try to get/set value of the myCustomList using myCustomList .objectReferenceValue = modifiedCustomList as List< MyCustomObject > tells me that List< MyCustomObject> cannot be cast as Object.

I tried to simply set the values through myCustomList = (target as TargetClass).myCustomList, but (of course) when I pressed the play button the objects instances were reset to a fresh new list.

How do I cast List to an Object? Or how to use the serializedObject to get/set data of types like Lists?

Upvotes: 5

Views: 3671

Answers (1)

Ray Garner
Ray Garner

Reputation: 932

Youll need to iterate through the object like so...

 SerializedProperty myCustomList = serializedObject.FindProperty ("myCustomList");

    for (int i = 0; i < myCustomList .arraySize; i++)
    {
        SerializedProperty elementProperty = myCustomList.GetArrayElementAtIndex(i);

        //Since this the object is not UnityEngine.Object you can not convert them the unity way.  The compiler can determine the type that way so.....

       MyCustomList convertedMCL = elementProperty.objectReferenceValue as System.Object as MyCustomList;
    }

Since SerializedProperty is not a UnityEngine.Object you can not convert them the unity way. The compiler can not determine the type that way.

A discussion on the subject can be found here.

Upvotes: 3

Related Questions