【问题标题】:Why is my IList read-only?为什么我的 IList 是只读的?
【发布时间】:2014-01-31 02:48:56
【问题描述】:

我正在制作游戏。我搜索对象中的所有子组件并从中创建一个列表,然后删除第一个条目,因为我不想要它。当我尝试删除第一个条目时发生错误。 google 上似乎没有这方面的内容,一切都是如何使它成为只读的。

我收到此错误:

NotSupportedException: Collection is read-only
System.Array.InternalArray__RemoveAt (Int32 index) (at /Users/builduser/buildslave/monoAndRuntimeClassLibs/build/mcs/class/corlib/System/Array.cs:147)
(wrapper managed-to-managed) UnityEngine.Transform[]:System.Collections.Generic.IList`1.RemoveAt (int)
PlayerEquipper.Start () (at Assets/PlayerEquipper.cs:27)

这是我的代码:

private IList<Transform> characterChilds = new List<Transform>();
private IList<Transform> armorChilds = new List<Transform>();
private IList<Transform> glovesChilds = new List<Transform>();
private IList<Transform> bootsChilds = new List<Transform>();



void Start()
{
    characterChilds = new List<Transform>();
    characterChilds = transform.GetComponentsInChildren<Transform>();
    Debug.Log(characterChilds[0]);
    characterChilds.RemoveAt(0);
    Debug.Log(characterChilds[0]);
}

【问题讨论】:

    标签: c# list unity3d ilist


    【解决方案1】:

    GetComponentsInChildren 方法似乎返回了一个不可变集合。您可以尝试以下解决方法:

    characterChilds = transform.GetComponentsInChildren<Transform>().ToList();
    

    【讨论】:

      【解决方案2】:

      你的这行:

      characterChilds = new List<Transform>();
      

      创建一个可变列表。但是,以下行:

      characterChilds = transform.GetComponentsInChildren<Transform>();
      

      覆盖该列表,因此前一行是无用的。显然,GetComponentsInChildren 返回一个不可修改的IList。如果你真的想从那个方法调用的结果开始,仍然可以修改列表,你可以试试:

      characterChilds = new List<Transform>(transform.GetComponentsInChildren<Transform>());
      

      现在,您可以从该列表中删除项目,但如果没有更多上下文,我不确定这是否会完全符合您的期望。

      【讨论】:

      • 谢谢!我了解现在正在发生的事情,并且您的解决方案运行良好。当它允许我时会接受你的回答。
      猜你喜欢
      • 2015-11-19
      • 2020-11-16
      • 1970-01-01
      • 2021-04-25
      • 2012-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多