Search code examples
c#unity-game-enginegame-physics

Destroy trail when finished


I have a missile with a trail renderer attached to it.

I want to destroy the game object (with the trail) after finishing the rendering process.

The code below does not work:

private TrailRenderer tr;


public void Start() {
    tr = GetComponent<TrailRenderer>();
}

public void Update() {

    if(tr) {

        if(tr.isVisible == false) {
            Destroy(this.gameObject);
        }
    }
}

Solution

  • I am assuming you wish to destroy the trail renderer when the duration of the final trail segment time has elapsed. If that is the case, as Eddge suggested, you should destroy after a delay once your missile is destroyed or stops moving:

    private TrailRenderer tr;
    
    void Start() {
        tr = GetComponent<TrailRenderer>();
    }
    
    public void MissileDestroyed()
    {
        Destroy(gameObject, tr.time);
    }