Untiy 访问组件(二)

来源:互联网 发布:北京工业大学 网络 编辑:程序博客网 时间:2024/06/14 00:27
查找游戏对象:

GameObject.Find(); 返回值类型:GamObject
可以查找任何层级物体,不受脚本绑定层级影响,,若指定层级,在指定层级中找,若不指定,则会在所有层级找,(名字不能重复),,如果存在多个物体重名,则会查找Hierarchy面板中最后创建的那个,,如果路径名没写全,不支持查找隐藏物体

transform.Find(); 返回值类型:Transform
只能查找子集物体,,如需查找其他层级,则要使用“完整路径”进行查找,,支持查找隐藏物体,,,(隐藏物体是指没有激活的物体,并不是看不见的物体)

通过标签查找:
通过Inspector 中的 Tag 标签查找物体
GameObject obj = GameObject.FindWithTag("AI");//通过Tag标签查找一个物体
GameObject obj = GameObject.FindGameObjectWithTag("AI");//通过Tag标签查找一个物体
GameObject[] obj = GameObject.FindGameObjectsWithTag("AI");//通过Tag标签查找一批物体

获取组件的方法
GetComponent<>(); //<脚本或者组件名>
GetComponentInChildren<>(); //<脚本或者组件名> 获取子物体组件列表
GetComponentsInChildren<>();
GetComponentInParent<>() ; //<脚本或者组件名> 获取父类物体组件列表
GetComponentsInParent<>(); //包括物体本身以及下面所有的子物体

// 代码示例void Start () {//print("start");//两点之间的距离//print(Vector3.Distance(Vector3.zero, new Vector3(3, 4, 0)));/*GameObject go;go = null;print(go.name);*///使用GameObject.Find可以通过层级关系查找到到未激活的游戏物体,如果不写层级关系,则找不到。//print(GameObject.Find("/Cube (2)/Cube (3)/Cube").name);/*使用Transform.Find()方法查找。只能查找其子级物体,不能越级。能查找隐藏的子级物体。能通过层级关系查找(隐藏)孙级物体Transform t = this.gameObject.transform.Find("/Cube (2)/Cube (3)/Cube");print(t.name);*///泛型方法的好处。print(GameObject.Find("/Cube (2)/Cube (3)/Cube").GetComponent<Transform>().localPosition);}// Update is called once per framevoid Update () {//print("update");// this.transform.Rotate(10, 10, 0);//物体旋转//平滑移动//this.gameObject.transform.position = Vector3.Lerp(this.transform.position, new Vector3(10, 0, 0), Time.deltaTime);//使用MoveTowards方法对物体进行移动//this.gameObject.transform.position = Vector3.MoveTowards(this.gameObject.transform.position, new Vector3(10, 0, 0), 0.05f);}