- Home /
GetComponentsInChildren always the same order
Is the array returned from http://docs.unity3d.com/Documentation/ScriptReference/Component.GetComponentsInChildren.html always in the same order?
Answer by Agustin Petrini · Apr 27, 2015 at 03:50 PM
For anybody landing here, it does: http://forum.unity3d.com/threads/getcomponentsinchildren.4582/#post-33983
And if it does not, I'm about to get into trouble ...
Answer by nirharpaz · Oct 08, 2015 at 11:32 AM
this is a long but reliable way as the default order is undefined. hope it helps
public SomeComponent[] Components;
private Transform _myTransform;
void GetChildrenByOrder()
{
SomeComponent[] temp = GetComponentsInChildren<SomeComponent> () as SomeComponent[];
Components = new SomeComponent[temp.Length];
int index = 0;
int noOfChildren = _myTransform.childCount;
for (int i=0; i<noOfChildren;i++)
{
SomeComponent childComponent = _myTransform.GetChild(i).GetComponent<SomeComponent>();
if(childComponent!=null)
{
Components[index] = childComponent;
index++;
}
}
}
the whole thing with _myTransform rather than just transform is for optimization. I call the object and claim the transform only once rather than every time.
Your answer
Follow this Question
Related Questions
grab weapon script problem 1 Answer
Storage of children references efficiency 1 Answer
GetComponentsInChildren not working 0 Answers
getComponentsInChildren counts fail after child destroying? 1 Answer
short script error mesige 1 Answer