Unity3d: Timed deletion of objects

facebooktwittergoogle_plusredditpinterestlinkedintumblrmail

This is a continuation of our last article, where we created ‘sticky’ objects in Unity3D, that could be thrown at surfaces with certain tags. Now we need to address the issue of timed deletion of objects, starting with some basics, and then moving onto some common issues.

Say we have a spawned bullet or charge that needs to disappear: the easiest thing would be to attach some code to its prefab which commences a countdown upon spawning, and deletes that object when the counter reaches 0.

There are more complex issues surrounding this, but for things like bullets, the code below should cover most of what is needed for simple deletion:

To get more complex: in reference to our last article, we’ll modify the ‘ThrowableScript’, so that once the object sticks to a tagged surface, it’ll commence a deletion countdown:

 

 

In the above code, we’re using a more ideal technique: a coroutine. This potentially allows us to time things more neatly than if we used the Update function. You’ll notice again, the coroutine was started when the collision code was triggered.

The line “Destroy(gameObject);” is what deletes the object. Most likely what you would see is the object suddenly vanishing. This isn’t always ideal. To build on these ideas, you can modify the below code, which fades the object out gradually, as the countdown commences. You’ll notice that the shader type is switched to Transparent/Diffuse as soon as the countdown is to commence: this is to allow the texture’s alpha component to be modified. We use a second coroutine to handle the fading.

 

 

fadingObjs

There are other tricks you can do, like sinking deletable objects downward into surfaces using Transform.Translate on the -Y axis, based off the height of the sinking object, and then deleting it when the height of the object has been traversed. You can even combine fading and sinking the objects.

2 Comments

  1. Pingback: Unity3D: Timed deletion of objects

  2. Good post. I’m experiencing a few of these issues as well..

Leave a Reply