- Home /
Question by
Der_Kevin · Nov 11, 2016 at 02:34 PM ·
gameobjecthierarchyfind
find next gameobject in hierarchy?
hey, how can i find find a GameObject that is under the current GameObject? so if the hierarchy is like this -root --obj1 --obj2 --obj3
i wanna do something like:
public class Findnext : MonoBehaviour {
public GameObject next;
// Use this for initialization
void Start () {
//if this script is on obj1 - next = obj2
//if this script is on obj2 - next = obj3
}
Comment
yes, getchild - of course but how do i get the next child under the current one?
Best Answer
Answer by TreyH · Nov 11, 2016 at 05:09 PM
using UnityEngine;
using System.Collections;
public class WhereIsThis : MonoBehaviour
{
// Use this for initialization
void Start ()
{
Transform nextChild = this.NextChild ();
if ( nextChild == null )
Debug.LogFormat ("{0} is the last sequential child or didn't have a parent!", this.name);
else
Debug.LogFormat ("{0} has a next sequential child named {1}!", this.name, nextChild.name);
}
// Update is called once per frame
private Transform NextChild ()
{
// Check where we are
int thisIndex = this.transform.GetSiblingIndex ();
// We have a few cases to rule out
if ( this.transform.parent == null )
return null;
if ( this.transform.parent.childCount <= thisIndex + 1 )
return null;
// Then return whatever was next, now that we're sure it's there
return this.transform.parent.GetChild (thisIndex + 1);
}
}
Your answer
Follow this Question
Related Questions
How to find which script disables my gameobject 1 Answer
Alternatives to GameObject.Find(); 1 Answer
Finding Children question 3 Answers
How do i find a bone on my character within a script? 2 Answers