2014-01-31 158 views
1

我在做一個遊戲。我搜索對象中的所有子組件,並從中創建一個列表,然後刪除第一個條目,因爲我不需要它。當我嘗試刪除第一個條目時發生錯誤。谷歌似乎沒有關於這一點,一切都是如何使其成爲只讀。爲什麼我的IList只讀?

我得到這個錯誤:

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]); 
} 

回答

1

這行你的:

characterChilds = new List<Transform>(); 

創建一個可變的列表。但是,以下行:

characterChilds = transform.GetComponentsInChildren<Transform>(); 

覆蓋該列表,因此上一行是無用的。顯然,GetComponentsInChildren返回不可修改的IList。如果你真的想從方法調用的結果開始,仍然能夠修改列表,你可以嘗試:

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

現在,您可以從列表中刪除項目,但沒有更多的情況下,我我不確定這會做到你想要的。

+0

謝謝!我明白現在發生了什麼,並且您的解決方案非常完美。接受你的答案,當它讓我。 – Jared

2

看來GetComponentsInChildren方法返回一個不可變的集合。您可以嘗試以下解決方法:

characterChilds = transform.GetComponentsInChildren<Transform>().ToList(); 
相關問題