How Add A Value to An Array; Issue

Hi there,
I have about couple of hundred objects that I want to add to an array. However using this code presents an error.

		memberScript[] members;
		foreach (memberScript child in someTransform){
		    members.Add(child);
		}

The error is that Add is not function in memberScript. I get that, but how then can I add child to the members array?

Don’t use an array if you want to dynamically add elements to it. Use a collection like List.

List<memberScript> members = new List<memberScript>(someTransform.childCount);
foreach (memberScript child in someTransform){
    members.Add(child);
}

Notice that I am using someTransform.childCount in the constructor. This is a small performance optimization if you know the element count you want to add in advance. If you don’t specify it, the list will grow dynamically (this also happens if you exceed the prespecified count).

Everything else works just like you know from arrays except that you use members.Count instead of members.Length to get the size of the list.

There’s probably a better way, but I would add a counter

        memberScript[] members;
        int count = 0;

        foreach (memberScript child in someTransform){

            members[count] = child;
            count++;
}

Hmm. You better follow Billykaters advice. It wasn’t there when I started. Otherwise you may need to size the array. I haven’t used them much yet.

Why would you bother enumerating the array manually? List has a constructor that takes an IEnumerable.

MemberScript[] members;
List<MemberScript> memberList = new List<MemberScript>(members);

Edit: As an aside - and the trend continues - this is not a Unity specific question and an answer could have easily been derived from some searching and research on your part.

Thanks,
So I switched the array to a list, however I can not seem to assign the looped variable to the list tho it is declared as the same class as the list.

        foreach (FEMemberScript child in moverTransform){
            members.Add(child);
        }

You could use LINQ, if the code makes any sense, which it doesn’t. Transform is IEnumerable, but it returns Transforms, not memberScripts.

memberScript[] members = someTransform.Cast<Transform>().ToArray();

http://forum.unity3d.com/threads/203245-Get-Children-example-code-Uses-quot-transform-quot-Unintuitive?p=1375070&viewfull=1#post1375070

memberScript[] members = someTransform.EnumerateChildren().ToArray();

Cool.
Thanks Jessy.