- Home /
How can i find Next and Previous Child ?
Hi guys,
Premise: I do not want to use an array to obtain a management easier and faster.
I expose my problem:
by Ray-Cast identify a GameObject (Current-Child - See photo)
Unity has in memory all the GameObject, How can I know the next child and previous child ?
Answer by Jake-L · Jun 15, 2013 at 09:11 PM
I don't know of any API method to achieve this, but it can be done:
Get the parent
Walk through it's children to find the index of current
Get the index below or above and you're done
C# Example to get the next child (or null if it doesn't exist)
Transform GetNext()
{
var myself=transform;
var parent=transform.parent;
var childCount=parent.childCount;
for (int i=0;i<childCount-1;i++) { // skip the last, as it doesn't have a successor
if (parent.GetChild(i)==myself)
return parent.GetChild(i+1);
}
return null;
}
Code is untested from head, but should work.
Hello Jake,
I'm sorry if I have not answered before.
I've seen the code, it is great also because I did not know GetChild (never seen in Unity's guide )
I understand that GetChild allows you to select the Child (GameObject) by index:
GetChild (0) is equal to > first element
GetChild (1) is equal to > second element
...
How can I know the index of the GameObject, intercepted with a ray-cast?
Here's an example:
var TestIndex = hit.collider.gameObject.transform.parent.gameObject.GetIndex();
("GetIndex" is invented. I used it to make you understand my idea)
If it were possible, I might find the next child and previous, simply adding GetChild(TestIndex + 1) or GetChild(TestIndex -1)
thanks Jake
I await your suggestion
Hi Jake,
I'm sorry if I have not answered before.
I've seen the code, it is great also because I did not know GetChild (never seen in Unity's guide )
I understand that GetChild allows you to select the Child (GameObject) by index:
GetChild (0) is equal to > first element
GetChild (1) is equal to > second element
...
How can I know the index of the GameObject, intercepted with a ray-cast?
Here's an example:
var TestIndex = hit.collider.gameObject.transform.parent.gameObject.GetIndex();
("GetIndex" is invented. I used it to make you understand my idea)
If it were possible, I might find the next child and previous, simply adding GetChild(TestIndex + 1) or GetChild(TestIndex -1)
thanks Jake
I await your suggestion
The for-loop is used to find the own index (if GetChild(i)==myself).