广告合作
  • 今日头条

    今日头条

  • 百度一下

    百度一下,你就知道

  • 新浪网

    新浪网 - 提供新闻线索,重大新闻爆料

  • 搜狐

    搜狐

  • 豆瓣

    豆瓣

  • 百度贴吧

    百度贴吧——全球领先的中文社区

  • 首页 尚未审核订阅工具 订阅

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

    来源:网络收集  点击:  时间:2024-02-22
    【导读】:
    Unity 实用技巧 之 GetChild快速获取物体子物体。本节介绍使用GetChild函数快速获取对象的子物体的简单案例,具体如下工具/原料moreUnityGetChild函数一、知识要点1/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/9

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

    2/9

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

    3/9

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

    4/9

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

    5/9

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

    6/9

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

    usingSystem.Collections;

    usingSystem.Collections.Generic;

    usingUnityEngine;

    publicclassGetChildTest:MonoBehaviour{

    publicTransformgo;

    //Usethisforinitialization

    voidStart(){

    }

    //Updateiscalledonceperframe

    voidUpdate(){

    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);

    }

    }

    privateTransformGetChild(Transformtr,intindex){

    returntr.GetChild(index);

    }

    }

    7/9

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

    8/9

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

    9/9

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

    注意事项

    您的支持,是我们不断坚持知识分享的动力,若帮到您,还请帮忙投票有得;若有疑问,请留言

    UNITYGETCHILD获取物体子物体
    本文关键词:

    版权声明:

    1、本文系转载,版权归原作者所有,旨在传递信息,不代表看本站的观点和立场。

    2、本站仅提供信息发布平台,不承担相关法律责任。

    3、若侵犯您的版权或隐私,请联系本站管理员删除。

    4、文章链接:http://www.1haoku.cn/art_103286.html

    相关资讯

    ©2019-2020 http://www.1haoku.cn/ 国ICP备20009186号05-05 05:05:57  耗时:0.025
    0.0255s