2016-11-19 66 views
0

我有點卡住了我的腳本。當一個附有我的腳本的遊戲對象有一個具有特定遊戲對象的觸發事件時,我想在一段時間後銷燬特定的遊戲對象。在團結一段時間後摧毀一個特定的遊戲對象

所以我來到了這一點:

void OnTriggerEnter (Collider other) { 

if (other.gameObject.tag == "leaf1"){ 
    StartCoroutine (LeafDestruction()); 
    } 
} 

IEnumerator LeafDestruction(){ 

yield return new WaitForSeconds (5); 
Destroy (gameObject); 

} 

我知道這是一個小白錯誤,但我想我錯過了什麼,因爲當我運行該腳本,它破壞了遊戲物體與它相連的腳本,而不是特定的gameObject(帶標籤)。

我該如何解決這個問題?

回答

3

一個簡單的辦法是使用Destroy函數的第二個參數:

if (other.gameObject.tag == "leaf1") 
     Destroy(other.gameObject, 5.0f) ; 
+0

謝謝!它工作正常,而且更簡單。 –

2

基本上你需要告訴你的協程,它應該銷燬other.gameObject而不是運行這個腳本的gameObject。

所以,你可以做的是一個參數添加到您的協程,通過在遊戲對象,它應該被銷燬:

void OnTriggerEnter (Collider other) { 

    if (other.gameObject.tag == "leaf1") 
    { 
     IEnumerator coroutine = LeafDestruction(other.gameObject); 
     StartCoroutine (coroutine); 
    } 
} 

IEnumerator LeafDestruction(GameObject toDestroy){ 
    yield return new WaitForSeconds (5); 
    Destroy (toDestroy); 
} 
+1

謝謝!它的作用也像Hellium的答案。 –

2

你摧毀了物體而不是葉子。 gameObject是this.gameObject的別名,它是此腳本組件附加到的遊戲對象。備註MonoBehaviour繼承自BehaviourBehaviour繼承自Component

GameObject leafObject; 

void OnTriggerEnter (Collider other) { 
    if (other.gameObject.tag == "leaf1"){ 
     leafObject = other.gameObject; 
     StartCoroutine (LeafDestruction()); 
    } 
} 

IEnumerator LeafDestruction(){ 
    yield return new WaitForSeconds (5); 
    Destroy (leafObject); 
} 
+0

您的解決方案也可以像其他人一樣工作,非常感謝:) –