- Home /
reversing an array? how to?
i want to convert from using arrays to lists
here is what i have so far:
//CREATE A TEMP ARRAY VAR (GENERIC LIST)
var tmpList = new List.<Transform>();
//GET ALL OBJECTS IN THE GROUP (BUILT IN ARRAY, VERY FAST/FIXED SIZE)
var members : Transform[]=object.parent.GetComponentsInChildren.<Transform>();
//REVERSE THE OBJECTS IN THE ARRAY
members.Reverse();
the problem is that GetComponentsInChilder gives me built in array that i cannot reverse. is there some easy way in reversing the array? or how i can do this differently?
thanks!
Answer by Waz · Sep 07, 2011 at 01:01 PM
You have to write:
System.Array.Reverse(members);
Answer by Joshua · Sep 07, 2011 at 01:06 PM
Say you have
Transform[] allChildren = GetComponentsInChildren< Transform >();
which you want to reverse. First you'd create a new array of equal size:
Transform[] tempArray = new Transform[ allChildren.Length ];
Now just assign each element at index i to length-(i+1)
for( int i = 0; i < allChildren.Length; i++ )
{
tempArray[ allChildren.Length - 1 - i ] = allChildren[ i ];
}
And then you copy the temp array into the original array to replace it.
allChildren = tempArray //allchildren is now reversed.
The classic implementation would be to swap from the ends to half way. Far less copying that way. Of course, that is why we should use system functions - they read $$anonymous$$nuth so we don't have to ;-)