I made a component that deletes the object using a coroutine timer

I figured the behavior for wanting projectiles and particle effects to delete themselves after a time could be handled by a single mechanism. I wanted to see if I really understood coroutines, so I tried this and added it to each of the impact effects and projectiles.

Projectiles got 20 seconds to find a target or perish. Impact effects would be configurable based on how long the effect is–I suspect I could make this look for a lifetime variable in the particle component, but I like how focused and clean this component is.

It works like a charm, and I can throw it onto anything without needing to edit other components.

public class SelfDestroyer : MonoBehaviour
{
[SerializeField] float lifetime = 10f;

// Start is called before the first frame update
void Start()
{
    StartCoroutine(DestroySelf());
}

IEnumerator DestroySelf()
{
    yield return new WaitForSeconds(lifetime);
    Destroy(gameObject);
}

}

It feels almost like “tagging” the item to have some common behavior. I think I’m starting to really understand how powerful components can be as function modules.

Oh, and I know you can just do Destroy(object, time); in the Start() and get the same effect, but this let me practice coroutines!

Fun fact: The Destroy(object, float) method creates a coroutine. :slight_smile:
Good job, by the way.

1 Like

Thank you for taking the time to respond here and in my other topics!

Nice attempt.

I (almost) never use coroutines myself: I find DOTween sequence easier to setup and more code readable (with DOTween being free of course)

Nice! I actually thought about doing this myself until I discovered the Destroy overload with the time variable. But yeah, it’s nice getting to practice stuff like this. I love when we get videos that let us just practice problem solving, it’s fun

1 Like

Custom destroyer is good sometimes, for instance the VisualEffects (graphs) dont have “isAlive” checks (unlike particle-system). You can only count active particles and that can remove your visual effect before triggering. Coupling coroutine with a safety mechanism of “is it playing” (does it have active particles), allows to garbage collect.
More than a hack than optimal solution tho.

Another benefit to this is not calling GetComponent<>, which, if you have a multi-projectile weapon, can eventually prove detrimental to performance if you want, say, more than 100 projectiles (but perhaps at that point one should look into Unity specific optimisation features like the ECS)

Privacy & Terms