Unity组件添加与销毁之简单笔记

本文介绍了在Unity中如何对游戏物体进行组件的添加、销毁及查找的方法。包括如何使用AddComponent和Destroy方法来操作组件,以及通过GameObject.Find方法获取指定名称的游戏物体,并进一步获取其组件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 private void AddAndDestoryComponent()
    {
        //添加
        gameObject.AddComponent<Image>();
        //销毁
        Destroy(gameObject.GetComponent<Image>());
        //引用
        gameObject.GetComponent<Image>();

        //其中,gameObject是可变的,可以是自身即,也可以是其它游戏物体的引用。
      apple.gameObject.GetComponent<Image>(); //gameObject代表的是apple自身,当然,实际代码中并不需要这样写
      apple.GetComponent<Image>();//通常写成这样,上例只是为方便理解

//大写开头GameObject 与gameObject的区别 //大写开头GameObject 是类,是class, 是苹果类,apples //gameObject 具体的个体,是对象,是这个苹果,apple //查找游戏物体GameObject GameObject.Find("apple");// 返回一个GameObject的对象 GameObject myApple= GameObject.Find("apple");//所以应该写成这样 //当然也可以写成这样,要根具需要 GameObject.Find("apple").GetComponent<Transform>(); //查找到游戏物体后获取该游戏物体的Transform组件,返回值是Transform类型的组件 Transform myTransform = GameObject.Find("apple").GetComponent<Transform>();//定义接收上例的返回值     

      //先引用
      GameObject myApple = GameObject.Find("apple");

      myApple.GetComponent<Button>();
      //后添加
      myApple.AddComponent<Button>();
      //用完销毁
      Destroy(myApple);


}

 

转载于:https://www.cnblogs.com/madinglin/p/8502544.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值