[Tip] Auto Destroy Particles When Finished Animating

Hi All.
I was busy thinking about how many ParticleSystems are left hanging around in the scene and did some hunting for a quick solution. There is a lot of stuff out there but this is the simplest I found. I am using unity 5.6.1 so my code may be different from the course code.

void PuffSmoke() {
    GameObject smokePuff = Instantiate(Smoke, transform.position, Quaternion.identity) as GameObject;
    //smokePuff.particleSystem.startColor = gameObject.GetComponent<SpriteRenderer>().color;
    var sP = smokePuff.GetComponent<ParticleSystem>().main;
    sP.startColor = gameObject.GetComponent<SpriteRenderer>().color;
    Destroy(smokePuff, sP.duration);
}

Destroy can take two options, GameObject and Time And since I already have the ParticlSystem().main stored in sP I have quick access to it’s duration. So below is all you need to add. this works for any duration. I don’t think it will work for looping particles though.

Destroy(smokePuff, sP.duration);

For older versions maybe try this. [Not tested]

void PuffSmoke() {
    GameObject smokePuff = Instantiate(Smoke, transform.position, Quaternion.identity) as GameObject;
    smokePuff.particleSystem.startColor = gameObject.GetComponent<SpriteRenderer>().color;
    Destroy(smokePuff, smokePuff.particleSystem.duration);
}
2 Likes

Privacy & Terms