How do I find the children of an object, and store them in an array?
I have a wall, with 4 points. I wan’t to be able to access these points, but in order to do that I need to have them in an array.
I use C#
How do I find the children of an object, and store them in an array?
I have a wall, with 4 points. I wan’t to be able to access these points, but in order to do that I need to have them in an array.
I use C#
For a one line method to get the array
Transform[] children = GetComponentsInChildren<Transform>();
Transform is also enumerable. So you can avoid the array altogether with:
foreach (Transform child in transform){
// Do something to child
}
Thank you for your answer, I works.... Kinda. When I use this 1 line method, I don't get the children only. I get the parent as well! Why??? My code: public GameObject test; public Transform[] points; void Update(){ points = test.GetComponentsInChildren<Transform>(); }
– BokaiiHere is the doc description: Returns all components of Type type in the GameObject or any of its children. If you want to remove the parent: var children = Array.FindAll(GetComponentsInChildren<Transform>(), child => child != this.transform); but I think the parent is always the first one so you could start iteration from second index (1). But I am not 100% sure about that.
– fafase[lambda expression][1] Its a weird, but very powerful C# language feature. [1]: http://msdn.microsoft.com/en-us/library/bb397687.aspx
– KiwasiBased on your questions I’ve seen here, you’d really benefit from spending an afternoon in the Learn Unity area of the website, where lots of tutorials address a ton of beginner’s questions while teaching good practices.
You probably want this:
Transform[] children = new Transform[transform.childCount];
for (int i=0; i<transform.childCount; i++) {
children*=transform.GetChild(i);*
}
List children = new List();
void Start()
{
foreach (Transform t in transform)
{
children.Add(t.gameObject);
}
}
IList<Transform> GetChildren(Transform transform) { return Enumerable.Range(0, transform.childCount) .Select(x => transform.GetChild(x)) .ToList(); }
– dpoly