OnCollisionStay2D with while loop

Hey guys,
so I want my object to destroy itself if its boundary overlaps with another objects boundary that has the tag “Bomb” or “Blob”. But somehow it doesn’t work. Here is my function

void OnTriggerStay2D(Collider2D coll) { while (coll.GetComponent<Collider2D> ().bounds.Intersects(gameObject.GetComponent<Collider2D> ().bounds) && coll.CompareTag("Bomb") || coll.GetComponent<Collider2D> ().bounds.Intersects(gameObject.GetComponent<Collider2D> ().bounds) && coll.CompareTag("Blob")) Destroy(gameObject); }

I don’t know why it doesn’t work.

OnTriggerStay already is called in a loop. It’s called after every FixedUpdate if the condition of colliding with something applies. And only in a FixedUpdate step, that condition might change, since that is where the physics engine updates positions and re-detects collisions. So you don’t have to do a loop to check whether or not the object is still colliding.

That being said… what are you even trying to accomplish? You loop is supposed to destroy its own object as soon as its condition is true, which means that the loop will not be continued a second time anyway. Well… to be exact, it will actually be endless because Destroy doesn’t work immediately, but rather destroys the object at the end of the frame. Which will never be reached, because your loop is still running endlessly.

Next up: Why are you checking whether or not bounds are intersecting? OnTriggerStay2D isn’t called if that is not the case anyway.

So you don’t want to use a loop because there is no sense in destroying the object multiple times, and thus, you don’t want to use OnTriggerStay2D either, because that is also a loop thing.
You simply want to use OnTriggerEnter2D.

void OnTriggerEnter2D(Collider2D collider)
{
  if(collider.CompareTag("Bomb") || collider.CompareTag("Blob")
  {
    Destroy(gameObject);
  }
}

And that’s it.

Make sure your Bomb and Blob object’s colliders are actually set to be triggers. Otherwise you have to check collision with OnCollisionEnter2D, not OnTroggerEnter2D, because… you know, that’s for triggers.