Unity3d获取物体下的子物体

分类栏目:unity3d教程

68

unity3d 获取 子物体的几种方法


(一)通过使用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()来找到物体

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

 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