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

2024-10-15 05:44:46

Unity 实用技巧 之 GetChild快速获取物体子物体。本节介绍使用GetChild函数快速获取对象的子物体的简单案例,具体如下

工具/原料

Unity

GetChild函数

一、知识要点

1、Transform.GetChild:1)功能简述publicTransformGetChild(intindex);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; }}

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

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

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

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

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

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

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

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

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

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

猜你喜欢