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 @   weigang  阅读(570)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示