Domanda

I'm making a game. I search through all child components in an object and make a list from it, then I remove the first entry because I do not want it. An error occurs when I try to remove the first entry. There seems to be nothing on google about this, everything is HOW to make it read-only.

I get this error:

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)

This is my code:

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]);
}
È stato utile?

Soluzione 2

This line of yours:

characterChilds = new List<Transform>();

Creates a mutable list. However, the following line:

characterChilds = transform.GetComponentsInChildren<Transform>();

Overwrites that list, and so the previous line is useless. Clearly, GetComponentsInChildren returns an IList that is not modifiable. If you really want to start from the result of that method call and still be able to modify the list, you can try:

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

Now, you can remove items from that list, but without more context, I'm not certain that will do exactly what you're hoping for.

Altri suggerimenti

It seems the GetComponentsInChildren method returns an immutable collection. You can try the following to workaround it:

characterChilds = transform.GetComponentsInChildren<Transform>().ToList();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top