Issue with Object Staying Collided

Hi everyone,

My code attempts to detect if the pizza in my game is collided with the user-controlled hand. If it is, then the hand will be able to add velocity to the pizza, effectively tossing it. However, I have colliders on the edge of the screen to prevent the pizza from flying off. When the pizza is collided with the edges, the hand can still add velocity to the pizza even though the hand isn’t actually touching it.

#pragma strict
var collided = false;
var thrust: float;
var pizza : Rigidbody2D;
  
  function Start() {
      //get the rigidbody of the pizza-small object
   pizza = GameObject.Find("pizza-small").GetComponent.<Rigidbody2D>();
  }
//hand + pizza collision detection
function OnCollisionStay2D(coll: Collision2D) {
     if (coll.gameObject.tag == "Pizza") {
         collided = true;
     }
     else {
         collided = false;
     }
}
function Update() {
     //constantly detects collision
     if (collided === true) {
         Debug.Log("Hand+Pizza");
     }
//Input
if (Input.GetKey(KeyCode.W)) {
     Debug.Log("Up");
     transform.position.y+= 0.2;
     if (collided === true) {
     //Adding force to the pizza
     pizza.velocity = Vector3(0,15,0);
     }
}
//left
else if (Input.GetKey(KeyCode.A) || Input.GetKey("left")) {
     Debug.Log("Left");
     transform.position.x-= 0.1;       
}
//right
else if (Input.GetKey(KeyCode.D) || Input.GetKey("right")) {
     Debug.Log("Right");
     transform.position.x+= 0.1;       
}
//down
else if (Input.GetKey(KeyCode.S) || Input.GetKey("down")) {
     Debug.Log("Down");
     transform.position.y-= 0.1;       
}
//moves the hand back to it's original position - gravity was wonky so I decided against using a rigidbody
else if (transform.position.y > -3.5) {
     transform.position.y-= 0.25;
}
else {
     collided = false;
}
}

The above script handles input and collision. Collided remains true when the pizza is collided with the edge colliders.

I only want the pizza to gain upward velocity if the hand is colliding with it, and I’m kind of stuck, any insight would be really appreciated!

OnCollisionStay is only called in frames when the collision is ongoing. If the collision stops it isn’t going to be called.

If you want to do something when a collision ends (i.e. set your boolean to false) you need to use OnCollisionExit

I’ve tried adding OnCollisionExit, but since I can’t put it inside of Update(), it appears to not solve anything as it doesn’t check collision constantly and I don’t know how to implement it.

Edit: I got it! I was using an if statement to detect the tag earlier, but since I removed that it works!