直接上代码如图物体排列顺序,脚本挂在了第一个Cube上,基于Hierarchy 中查找,从上往下查找

unity:unity 在场景中查找物体

直接上代码

  void Start()
    {

        Transform transform= this.transform.GetChild(0); // 获取第一个子物体 括号里面只能是int类型,不**也可以
        Transform name1 = this.transform.Find("Cube1/Cube2");//使用transform.find只能查询自身下一级的子物体,且子物体是否**都能查到,若查询多级的子物体则加'/'
      //  Transform name2 = transform.Find("Cube");//这个跟transform.find一样 本人用的是2018.3.0 这个方法已经舍弃但是可以用
        Debug.Log(transform.name);
        Debug.Log(name1);
      //  Debug.Log(name2.name);
        GameObject name4 = GameObject.Find("Cube");//场景中所有的物体,但是必须是**的
        GameObject name5 = GameObject.FindGameObjectWithTag("Cube");//根据tag查找物体,但是必须是**的
        GameObject[] name6 = GameObject.FindGameObjectsWithTag("Cube");//根据tag查找同一tag的物体,但是必须是**的
        Debug.Log(name4);
        Debug.Log(name5);
        Debug.Log(name6.Length);
        Transform name3 = FindObjectOfType(typeof(Transform)) as Transform;//在场景中查找有transform组件的物体,必须是**的,只查场景中找第一个带有Transform 组件的物体
        Transform[] name = FindObjectsOfType(typeof(Transform)) as Transform[];//在场景中查找有transform组件的物体,必须是**的
        Debug.Log(name3.name);
        Debug.Log(name.Length);
    }

运行结果如下:

unity:unity 在场景中查找物体

 

相关文章: