如何将List<T>转换为对象

5

我决定在Unity中为我的组件制作一个自定义编辑器。

这个组件本身有一个对象列表,我已经声明为List。

编辑器通过以下方式对其进行定位:

myCustomList = serializedObject.FindProperty ("myCustomList");

问题在于,当我尝试使用myCustomList .objectReferenceValue = modifiedCustomList as List< MyCustomObject >获取/设置myCustomList的值时,它告诉我无法将List< MyCustomObject>强制转换为Object。
我尝试简单地通过myCustomList = (target as TargetClass).myCustomList设置值,但(当然)当我按下播放按钮时,对象实例被重置为一个全新的列表。
如何将List转换为对象?或者如何使用serializedObject来获取/设置像List这样的数据类型的数据?

那么,为了澄清您的问题,您是在问为什么无法将modifiedCustomList强制转换为List<MyCustomObject>,这意味着您最初只有一个对象列表,并希望将它们转换为自定义对象,但似乎无法进行强制转换? - Matthew Cox
1个回答

3
你需要这样遍历对象...
 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;
    }

由于SerializedProperty不是UnityEngine.Object,因此您无法按照unity的方式进行转换。编译器无法以这种方式确定类型。

有关此主题的讨论可以在这里找到。


我会尝试一下,看起来非常有前途! - Creative Magic
对我有用。希望一切顺利。 - Ray Garner
无法将elementProperty的objectReferenceValue真正转换为MyCustomObject... 现在正在寻找一种方法来解决这个问题。 - Creative Magic
我编辑了答案,包括一种让您转换为自定义对象的方法。 - Ray Garner
1
问题在于我的值对象类和具有扩展编辑器的类将这些字段设置为internal,这就是为什么它总是返回null - Creative Magic
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接