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


}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM