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

 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