Search code examples
androidunity-game-enginegame-physics

unity OnTriggerExit2D doesn't work always


I have small unity game, where I instantiate finger clone from a prefab that has movement and animation script attached to it, a box collider object equal to view port size that detects collisions, and an increase object counter (i.e, counter of no of cloned instance of finger showing on screen).

Object are coming on screen in random intervals from 1 to 3 seconds and player has to hold the finger until next object comes. If the screen goes blank, it is a game over.

To implement this logic I have used box2d collider the same size as viewport, and attached a box2d collider to finger.

OnTriggerEnter2D alway increments the static object counter value but isn't always triggered. where i need to destroy object

Finger object also has an animation attached to it but it only plays when finger is held or pressed by the player, not when the object enters or exits the screen.

Here's code for the finger object:

    using UnityEngine;
    using System.Collections;
    public class checkCollisionwithBox : MonoBehaviour {
        bool collided = false;

        void OnTriggerEnter2D(Collider2D other) {
            if (other.gameObject.tag == "mesh") {
                if (this.collided == false ) {      
                   GameController.GoodFingerOnScreen++;
                   this.collided = true;
                }
              }
           }
        void OnTriggerExit2D(Collider2D other) {
          if (other.gameObject.tag == "mesh") {
            if (GameController.GoodFingerOnScreen != 0) {   
                GameController.GoodFingerOnScreen--;
             }
           Destroy (this.gameObject);
         }
       }
   }

Solution

  • try the option of continuous detection in the rigid-body component under collider detection , otherwise if that doesnt help make sure the fingers are always out of the trigger by using some debug.log or checking inside the scene view.