Unity 实用技巧 之 GetChild快速获取物体子物体

 时间:2026-02-13 07:47:28

1、Transform.GetChild:

1)功能简述

public Transform GetChild(int index);

index:Index of the child transform to return. Must be smaller than Transform.childCount.

Returns Transform :Transform child by index.

Returns a transform child by index.

2)使用案例

 using UnityEngine;

 using System.Collections;public class ExampleClass : MonoBehaviour{

    public Transform meeple;

    public GameObject grandChild;    public void Example()    {

        //Assigns the transform of the first child of the Game Object this script is attached to.

        meeple = this.gameObject.transform.GetChild(0);        //Assigns the first child of the first child of the Game Object this script is attached to.

        grandChild = this.gameObject.transform.GetChild(0).GetChild(0).gameObject;

    }

 }

1、打开Unity,新建一个工程,具体如下图

Unity 实用技巧 之 GetChild快速获取物体子物体

2、在场景中,新建一个“GameObject”,在其下再新建一个“Cube”和“Sphere”,适当调整他们的布局,具体如下图

Unity 实用技巧 之 GetChild快速获取物体子物体

3、把“GameObject”下的子物体“Sphere”隐藏,具体如下图

Unity 实用技巧 之 GetChild快速获取物体子物体

4、在工程中,新建一个脚本“GetChildTest”,双击脚本或者右键“Open C# Project”打开脚本,具体如下图

Unity 实用技巧 之 GetChild快速获取物体子物体

5、在“GetChildTest”脚本上编写代码,首先设置一个变量获取对象,然后在Update函数里按下“A”键,打印第一个子物体的名称,按下“S”键,打印第二个子物体的名称,并显示该物体,具体如下图

Unity 实用技巧 之 GetChild快速获取物体子物体

6、“GetChildTest”脚本具体内容如下:

using System.Collections;      

using System.Collections.Generic;

using UnityEngine;

public class GetChildTest : MonoBehaviour {

    public Transform go;

    // Use this for initialization

    void Start () {

            }

        // Update is called once per frame

    void Update () {

        if (Input.GetKeyDown (KeyCode.A)) {

            print (GetChild (go, 0).name);

        }        if (Input.GetKeyDown (KeyCode.S)) {

            GetChild (go, 1).gameObject.SetActive (true);

            print (GetChild (go, 1).name);

        }

    }

    private Transform GetChild(Transform tr, int index){

        return tr.GetChild (index);

    }

}

7、脚本编译正确,回到Unity界面,把脚本赋给“GameObject”,并把“GameObject”赋给脚本对应变量,具体如下图

Unity 实用技巧 之 GetChild快速获取物体子物体

8、运行场景,按下“A”“S”键,控制台console打印信息,并且“Sphere”显示,具体如下图

Unity 实用技巧 之 GetChild快速获取物体子物体

9、到此,《Unity 实用技巧 之 GetChild快速获取物体子物体》讲解结束,谢谢

  • unity摄像机视野怎么设置为最低
  • Unity 实用技巧 之 简便的物体一波一波自动生成
  • C#如何编写一个创建SqlCommand对象的方法
  • Maya三维模型怎样插入循环边?
  • winrar如何分卷压缩
  • 热门搜索
    奇迹三代翅膀怎么合成 血热怎么办 财务报告怎么写 电脑蓝牙怎么打开 红牛喝多了会怎么样 喝酒喝多了怎么办 嘴巴起泡怎么办 德尔地板质量怎么样 新鞋磨脚后跟怎么办 蜂蜜怎么储存