Search code examples
c#unity-game-engineparticlesparticle-system

How can I destroy a game object but have a particle effect after in unity3D?


I am now making a simple game and when the enemy dies it emit particles. But the problem is that once it has been destroyed then the particle effect stops. Is there a way to solve this problem? Any help is greatly appreciated! I am now using Unity 2019.3.9f1. Here is my code (enemy) -----

private void OnCollisionEnter(Collision collision)
{

    if (collision.gameObject.CompareTag("bomb"))
    {
        GetComponent<ParticleSystem>().Play();
        Destroy(enemy);
    }
}

Solution

  • One option is to instantiate the particle system before destroying the gameObject (creating new GameObject), and assign a lifetime to this new GameObject:

    Destroy(newGameObject, secondsToDestroy);
    

    You can also do something similar to: https://answers.unity.com/questions/610673/how-to-destory-a-gameobject-in-c-after-3-seconds.html

    UPDATED

    public ParticleSystem ps;
    
        // Start is called before the first frame update
        void Start()
        {
            GameObject go = Instantiate(ps.gameObject);
            Destroy(go, 10.0f);
            Destroy(this.gameObject);
        }