Unity查找物体和组件的方法

一、找物体:
①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<>()
 
③Transform:
已知层级:在他的直接孩子中查找
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面板中进行赋值
 
 
 
posted @ 2024-05-21 15:09  weigang  阅读(25)  评论(0编辑  收藏  举报