Block Breaker: How to destroy the exhausted smoke instances

Hey Guys.

When I got to the end of Block Breaker and ran it on auto-play I noticed that the smoke on each destroyed block would play but the instance would still be in the Hierarchy. Every time a new block was destroyed with smoke particles, the smoke instance would stay in memory. So with a game of 40 blocks that got destroyed 40 instances of the smoke particles would be in memory and in the Hierarchy list doing nothing.

The code below destroys the smoke particle instances after they have finished animating. I have included plenty of comments to hopefully make it easy to understand. The only new bit of code if after the //Destroy The Extinguished Smoke Instance line.

EDIT: The code is for the PuffSmoke method in brick.cs

void PuffSmoke()            //Create the smoke
    {

    //Create a new instance of the smoke in the location of the brick & name it 'smokePuff'.
    GameObject smokePuff = Instantiate(smoke, transform.position, transform.rotation) as GameObject;

    //Set the colour of the smoke instance called 'smokePuff' to the same as the brick colour.
    smokePuff.GetComponent<ParticleSystem>().startColor = gameObject.GetComponent<SpriteRenderer>().color;

    //Destroy The Extinguished Smoke Instance
    //---------------------------------------
    //Create a variable 'smokeLife' to hold the length of time the smoke will be visible. 
    float smokeLife = smokePuff.GetComponent<ParticleSystem>().duration + smokePuff.GetComponent<ParticleSystem>().startLifetime;
    //Destroy the 'smokePuff' instance after it has finished its animation. 
    Destroy(smokePuff, smokeLife);        

    }   //PuffSmoke() -end`

A big thanks to Baste on the Unity forums who helped me out :wink:

2 Likes

I got similar issue with animations in my own game. I made a new script pinned to all objects I wanted to delete from hierarchy after some period of time.

>> See the script <<

You could attach a script to the particle prefab to destroy the object after a set time. Then they would clean up after themselves.

1 Like

Simple and effective, I shall investigate the bits that are new to me and then try and implement it in mine. Thanks for this post :slight_smile:

1 Like