【问题标题】:How to convert List<T> to an Object如何将 List<T> 转换为对象
【发布时间】:2014-08-01 04:48:10
【问题描述】:

在 Unity 中,我决定为我的组件制作一个自定义编辑器。
组件本身有一个我已声明为 List 的对象列表。

编辑器的目标是这样的:

myCustomList = serializedObject.FindProperty ("myCustomList");

问题是,当我尝试使用myCustomList .objectReferenceValue = modifiedCustomList as List&lt; MyCustomObject &gt; 获取/设置myCustomList 的值时,告诉我无法将 List 转换为 Object。

我尝试通过 myCustomList = (target as TargetClass).myCustomList 简单地设置值,但是(当然)当我按下播放按钮时,对象实例被重置为一个全新的列表。

如何将 List 转换为 Object?或者如何使用serializedObject来获取/设置Lists等类型的数据?

【问题讨论】:

  • 所以为了澄清您的问题,您是否在问为什么不能将 modifiedCustomList 转换为 List&lt;MyCustomObject&gt;,这意味着您从仅包含对象的列表开始,并希望将它们转换为您的自定义对象,但似乎无法投射它们?

标签: c# unity3d


【解决方案1】:

你需要像这样遍历对象...

 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 您不能以统一的方式转换它们。编译器无法通过这种方式确定类型。

可以在here找到有关该主题的讨论。

【讨论】:

  • 我试试看,看起来很有希望!
  • 为我工作。希望一切顺利。
  • 无法真正将 elementProperty 的 objectReferenceValue 转换为 MyCustomObject... 正在尝试寻找一种方法来做到这一点
  • 我编辑了答案以包含一种让您投射到自定义对象的方法。
  • 问题是我的值对象类和具有扩展编辑器的类将这些字段作为internal 访问,这就是为什么它总是返回null
猜你喜欢
  • 2011-08-05
  • 2019-10-03
  • 2014-02-05
  • 1970-01-01
  • 2017-08-20
  • 1970-01-01
  • 2019-04-13
  • 1970-01-01
  • 2019-02-03
相关资源
最近更新 更多