在U3D中查找物体和组件的方式

一、找物体:
①GameObject:
a.Find(string name)通过物体的名字查找
b.FindWithTag(string tag);通过标签获取添加该标签的一个物体
c.FindObjectOfType();依据组件类型
d.FindGameObjectsWithTag(string tag)通过标签获取所有添加该标签的物体数组
②Transform:
a.获取到物体的Transform组件。然后Transform.gameObject;
③任意Component:
a.Compontent有个公开的成员变量GameObject


二、找组件:
①GameObject:
获取到GameObject–>拿到成员transform–>利用Transform中的方法查找组件
②Component:
a).GetComponent()
b).GetComponentInChildren
c).GetComponentInParent

d).GetCompontents
e).GetComponentsInChildren
f).GetComponentsInParent

g.FindObjectOfType()依据组件类型
h.FindObjectsOfType()

③Tansform:

已知层级:在他的直接孩子中查找
a.Find(string name)
b.FindChild(string name)
c.GetChild(int index)

未知层级,已知组件名字:

public static Transform GetChild(Transform transform,string name)
        {
            Transform targetTF = transform.FindChild(name);
            if(null != targetTF) return targetTF;
            Transform[] arr = transform.GetComponentsInChildren<Transform>();
            for (int i = 0; i < arr.Length; i++)
            {
                    targetTF = arr[i].FindChild(name);
                    if (null != targetTF)
                    return targetTF;
            }
            return null;
        }

使用公开成员变量,在Unity的Inspector面板中进行赋值


版权声明:本文为PirateCode原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。