2016-11-19 1 views
0

저는 지금 당장 스크립트를 사용하고 있습니다. 내 스크립트가 첨부 된 gameObject에 특정 gameObject가있는 트리거 이벤트가 있으면 시간이 지나면 특정 gameObject를 파괴하려고합니다. 시간이 지나면 특정 gameobject가 파괴됩니다.

그래서 나는이 온 :

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의 별칭이며이 스크립트 구성 요소가 첨부 된 게임 개체입니다. MonoBehaviourBehaviour에서 상속 받고 BehaviourComponent에서 상속됩니다.

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

당신의 솔루션은 다른 것과 마찬가지로 작동합니다. –

관련 문제