- Home /
Get an array of children from an existing array
Hi,
I am trying to access the child Transforms of an existing array of Transforms.
So right now I have a heirarchy that is:
Slots
slot 1
slot 2
slot 3
slot 4
I have an array which holds all of the Transforms of the 'Slots' gameObject above.
Each slot can also have a child gameObject, which will be called various names (Cheese, Ham, Coke, Lemonade).
I would like to iterate through each child of each slot (1,2,3,4) to enable me to compare this in code.
How do I create an array of Transforms, populated with the child Transforms of an existing array of Transforms?
Code being used is C#.
Any pointers would be appreciated, I have only ever created basic arrays to iterate through but I seem to be struggling with using an existing array to populate a new array. I am sure there must be a fairly simple way to do this.
Thanks,
Stephen.
Answer by Kesac · Nov 30, 2017 at 09:52 PM
Instead of using an array, you may want to look at using a generic List.
Once you have a list, you can do the following to get a list of elements that meet a certain criteria (in the below instance, the name property of the element is equal to Whatever):
filteredList = masterList.FindAll(element => element.name == "Whatever")
Another example (using transforms)
List<Transform> masterList = new List<Transform>();
masterList.Add(transform1);
masterList.Add(transform2);
// keep on adding transforms however you want
// Get a list of transforms with an x position between 5 and 10
List<Transform> filteredList = masterList.FindAll(t => t.position.x >= 5.0f && t.position.x <= 10.0f);
// Another way to loop through, this does almost exactly the same thing as the above line
List<Transform> filteredList2 = new List<Transform>();
foreach(Transform t in masterList)
{
if (t.position.x >= 5.0f && t.position.x <= 10f) filteredList2.Add(t);
}
// Now get the third member of the list
if (filteredList.Count >= 3) // Need this to make sure there are actually 3 members in the list
{
print(string.Format("The third member of the List is named {0}", filteredList[2].gameObject.name));
}
More information about Lists: https://msdn.microsoft.com/en-us/library/6sh2ey19.aspx
Your answer
Follow this Question
Related Questions
IndexOutOfRangeException help on debug 3 Answers
Add to Array 1 Answer
Array empties values on RunTime? 1 Answer
Array with two values per element 1 Answer
How do I print each element of a string array separately to a UI text box 2 Answers