Destroy 函式為物件消除的方法,也就是將場景中的物件移除,當場景不在需要這個物件時,為了避免物件留存場景中佔資源、耗費記憶體、吃效能等等,把物件從場景中移除就很重要了!
Destroy 常與 Instantiate 配合使用,常見的使用案例很多,例如射擊遊戲的子彈發射與子彈消除、遊戲的 UI 介面的開啟與關閉、怪物的重生與死亡消失等等。
除了消除物件之外,Destroy 也能消除物件的屬性,可搭配 GetComponent 方法取得。
● 定義:
參數說明:● obj:要消除的物件或屬性,這個物件或屬性必須存在於場景中。● t:消除的延遲時間,預設值是 0 秒,也就是立即消除,若為 1 則程式呼叫後過一秒之後消除。
● 用法:
//消除場景中的子彈 (立即消除)Destroy(bullet); //消除場景中的怪物屍體 (三秒後消除)Destroy(monster,3.0f);
● 實做(一):射擊遊戲的子彈物件消除
using UnityEngine;using System.Collections; public class Bullet: MonoBehaviour{ void Start() { Destroy(this.gameObject,2.0f); //在這個子彈物件生成後,過兩秒後自動消除 }}
● 實做(二):方塊被子彈打到後,消除子彈和方塊的碰撞屬性,五秒後消除方塊
using UnityEngine;using System.Collections; public class Bullet: MonoBehaviour{ void OnTriggerEnter(Collider col) { if (col.tag == "Cube") { BoxCollider collider = col.GetComponent<BoxCollider>(); Destroy(this.gameObject); //消除子彈 Destroy(collider); //消除方塊物件的 BoxCollider 屬性 Destroy(col.gameObject,5.0f); //5秒後消除方塊物件 } }}
● 實做(三):按下按鈕打開背包介面,在按一次則關閉
using UnityEngine;using System.Collections;using UnityEngine.UI; public class BagButton: MonoBehaviour{ public Button bagButton; //背包圖示按鈕 public UIBag bagPrefeb; //背包物件 Prefeb void Start() { bagButton.GetComponent<Button>.onClick.AddListener(ClickEvent); //按鈕事件 } void ClickEvent() { var UIbag = GameObject.Find("UIBag"); //尋找場景中的背包介面 if (UIbag) //存在 { Destroy(UIBag); //消除 } else //不存在 { Instantiate(bagPrefeb); //生成 } }}
------------------------------------------------說明--------------------------------------------------
- 參數 t 的單位為秒數,若沒有特別指定,預設是 0 秒,也就是一呼叫這個方法,物件立即被消除。
- 要進行 Destroy 的物件必須存在於場景中,可以搭配 GameObject.Find 系列方法去找到要消除的物件。
- Destroy 的物件型別為 Object,因此可以用來把物件(GameObject)從場景中移除,或是把屬性(Component) 從物件上移除。可以用 GetComponent<>() 方法來找到屬性。
Destroy 函式常搭配著生成物件的方法,詳細說明請見 Instantiate方法。
Try it and have fun!
請先 登入 以發表留言。