Moving out of collision with trigger using while loop crashes Unity.

I’m trying to move a game object to the left until it is no longer touching a trigger using a while loop in the OnTriggerEnter2D function, but it crashes Unity. Here’s my code:

void OnTriggerEnter2D(Collider2D c) {
        if(c.gameObject.tag == "Player")
        {
            while(c.IsTouching(transform.GetComponent<BoxCollider2D>()))
                c.transform.Translate(new Vector2(-1f, 0));
        }
    }

Anyone know why?

@micacer48 This could be because the collider at the moment it enters only “check” the first contact, but the next are checked all the time and this gives an overload loop, instead that, try using it inside a FixedUpdate (this suites better for movement) and only use the OnTriggerEnter to check if there was any “touch”, something like this:

bool inTouch;

void OnTriggerEnter ( Collider other) {
    if ( other.tag == "Player") {
         inTouch = true;
    }
}

void OnTriggerExit ( Collider other) {
    if ( other.tag == "Player") {
         inTouch = false;
    }
}

void FixedUpdate () {
    if ( inTouch ) {
        //Here goes the movement;
    }
}

The IsTouching method works a lot better inside an OnTriggerStay, this is like an Update, but with less ticks.

Hopes this helps, cheers.