Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert List<T> to an Object

Tags:

c#

unity3d

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?

like image 875
Creative Magic Avatar asked Oct 20 '22 04:10

Creative Magic


1 Answers

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.

like image 126
Ray Garner Avatar answered Nov 01 '22 09:11

Ray Garner