2014-07-23 53 views
0

我獲得了代碼的這個snippit,它實例化了一個粒子系統預製。我遇到的問題是克隆在5秒延遲後不會被破壞。任何建議表示讚賞。Unity C#4.5.2 2D銷燬實例化的粒子系統預製

private ParticleSystem instantiate(ParticleSystem prefab, Vector3 position) 
{ 
    ParticleSystem newParticleSystem = Instantiate(
     prefab, 
     position, 
     Quaternion.identity 
     ) as ParticleSystem; 

    if(newParticleSystem.gameObject != null) 
    { 
     Destroy(
      newParticleSystem.gameObject, 
      newParticleSystem.startLifetime 
      ); 
    } 

    return newParticleSystem; 
} 

回答

1

您的代碼依賴於稱爲ParticleSystem的任何東西來跟蹤何時銷燬系統。我會做的是這樣的:

private ParticleSystem instantiate(ParticleSystem prefab, Vector3 position) 
{ 
    ParticleSystem newParticleSystem = Instantiate(
     prefab, 
     position, 
     Quaternion.identity 
     ) as ParticleSystem; 

    newParticalSystem.AddComponent<TimedDestroy>().delay = newParticleSystem.startLifetime; 

    return newParticleSystem; 
} 

,然後添加這個腳本到您的項目:

using UnityEngine; 
public class TimedDestroy : MonoBehaviour 
{ 
    public float delay; 

    void Start() 
    { 
     Invoke("destruct",delay); 
    } 

    public void destruct() 
    { 
     Destroy(gameObject); 
    } 
}