- Home /
Return array of transform
Hello, I'm currently coding a function which will return a array of children. But I can't figure out how to return an array of children. This is the code I have so far:
//Find multiple children
Transform[] FindChildrens(Transform parent)
{
foreach (Transform child in parent.transform)
{
return child;
}
return null;
}
Answer by ifdef_ben · Mar 15, 2017 at 05:11 PM
The thing wrong with your approach is that you are returning a single element, not an array.
As @Bunny83 pointed out in the comments, you could get the transform's children array by simply calling:
parent.Cast<Transform>().ToArray();
But doing so would generate a lot of garbage. If you need an efficient way to get the children array you could get it by using the GetChild() method in a for loop.
Transform[] FindChildrens(Transform parent)
{
//Declaring an array the size of the number of children
Transform[] children = new Transform[parent.childCount];
for (int i = 0; i < children.Length; i++)
{
//populating the array
children[i] = parent.GetChild(i);
}
//returning the array. If there is no children it will be an empty array instead of null.
return children;
}
While your answer does answer the question and is providing a working solution, your second point is actually not true ^^. The Transform class implements the IEnumerable interface which let you iterate over the immediate children of the transform object.
The method could even implemented in one line:
using System.Linq;
// [ ... ]
Transform[] FindChildrens(Transform parent)
{
return parent.Cast<Transform>().ToArray();
}
Though the IEnumerable ultimatively also just uses childCount and GetChild. However the IEnumerator object that is required will allocate additional garbage. Also ToArray would use some sort of dynamic "List" to be able to collect all items and turn them into an array. So there's even more garbage to collect.
So performance-wise your solution is the better one.
ps: If you want to get "null" as return if there are no children, just add this at the very beginning of the "FindChildrens" method:
if (parent.childCount == 0)
return null;
That is really good to know. I was not aware of this, thank you! I corrected my answer.
Answer by Matt1000 · Mar 16, 2017 at 10:46 AM
This is probably the way to go:
GameObject parentObject;
Transform[] childernTransforms = new Transform[parentObject.transform.childCount];
for (int i = 0; i < parentObject.transform.childCount; i++) {
childernTransforms [i] = parentObject.transform.GetChild (i);
}
And thats all. Hope it helps :)
Your answer
Follow this Question
Related Questions
Why do we access children through an object's transform? 2 Answers
How to sync child objects of a transform in multiplayer 3 Answers
move enemy to random transform array 2 Answers
Instantiate from array into array? 2 Answers
get nearest game object 1 Answer