How to remove/freeze timer on Destroy()

Is there a way to stop remove or stop the Destroy() timer(aka. timeToDestroy) when the object leave the collider?

void OnTriggerEnter2D(Collider2D other)
    {        
    if (other.gameObject.tag=="trash")
            {
                Destroy(this.gameObject, timeToDestroy);
            }
    }

Hello.

For what i think you are trying to get, dont use Destroy like this.

You should Use OnTriggerStay2D()

So each frame is inside the collider this methid is executed.

   float timer = 5;

   void OnTriggerStay2D(Collider2D other)
     {        
     if (other.gameObject.tag=="trash")
             {
                 if (timer > 0) timer -= Time.deltaTime;
                 else Destroy(gameObject);
             }
     }

   void OnTriggerExit2D(Collider2D other)
    {
     timer = 5;
    }

So time goes down. and if reaches 0 the object is destroyed.

Bye!

Free tip: no need to type this.gameObject. Using directly gameObject (not GameObject) means the object that contains this scrip. Same for transform (not Transform) , GetComponent<>() …

Maybe you could use the OverlapCollider method which returns a list of all colliders that overlap this collider, and only use Destroy() if they stay in it for timeToDestroy time ?

Or use Detroy() in a Coroutine and stop the coroutine if the object leaves the collider with OnTriggerExit ?

I’m a neophyte so those ways might not be optimal.