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);
             }
     }
 
              Answer by tormentoarmagedoom · May 13, 2019 at 03:13 PM
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() ...
Answer by sebkah · May 12, 2019 at 09:42 PM
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.
Your answer
 
             Follow this Question
Related Questions
reset destroyed collider after game restart 1 Answer
one time Trigger and I get two OnTriggerEnter2Ds and two OnTriggerExit2Ds 0 Answers
How to identify which collider generated OnTriggerEnter2D 0 Answers
How to identify a single enemy game object? 0 Answers
OnTriggerEnter2D at high velocity 0 Answers