Unity获取物体下的子物体

Unity获取当前物体的所有子物体

(一)通过使用GetComponentsInChildren()

我们首先先创建一个脚本,在其中Start()方法中添加如下代码

void Start () {
        Transform[] father = GetComponentsInChildren<Transform>();

        foreach (var child in father)
        {
            Debug.Log(child.name);
        }
    }

再将脚本附到对应物体启动即可(如图是Father物体)

结果如下:

我们可以看到Father物体下的所有子物体包括孙物体也都显示出来了


那么如果我们只要Father物体下的子物体,而不要孙物体呢,该如何实现呢?

我们创建如下脚本将其添加到Father物体上,并将Father物体拖动到脚本上的Transform上

    public Transform father;

    public void Start()
    {       
        for (int i = 0; i < father.childCount; i++)
        {
            var child = father.GetChild(i).gameObject;
            Debug.Log(child.name);
        }
    }

运行结果如下:

(二)通过 GameObject.FindGameObjectsWithTag()来找到物体

这个方法只适用于给需要查找的物体提前打过标签tag才可以,比如我们给上面的三个子物体Son、Son1、Son2添加标签“erzi”

然后我们再新创一个脚本,代码如下:

 public Transform father;
    void Start()
    {
       /* GameObject name2 = GameObject.FindGameObjectWithTag("erzi");*/
        GameObject[] name3 = GameObject.FindGameObjectsWithTag("erzi");
       // Debug.Log(name2);
        foreach(var son in name3)
        {
            Debug.Log(son.name);
        }
    }

运行结果如下:

细心的朋友肯定可以看到上面代码有二行注释掉的,第一次调用函数时没注意调用错了…不仔细看真的容易错,使用FindGameObjectWithTag 由于有三个物体打上了”erzi”的标签,实际只能找出一个,所以找的时候是把最后一个物体找出。
如果运行注释掉的那两句话,结果是Son3

猜你喜欢

转载自blog.csdn.net/wangjianxin97/article/details/81704670