Hi! I’m experiencing some problems with collision detection.
I have this code to detect whether or not my gameobject collides with other objects or not:
public int collisionCount=0;
void OnTriggerEnter2D (Collider2D hit){
if (hit.collider2D.tag=="obj") {
collisionCount++;
Debug.Log ("collision++");
}
}
void OnTriggerExit2D (Collider2D hit){
if (hit.collider2D.tag=="obj") {
collisionCount--;
Debug.Log ("collision--");
}
}
So this way when collisionCount=0 I know that my gameobject doesn’t collide with any gameobject with tag “obj”. And it works! But when I spawn a gameobject with tag “obj” directly in the collider of my main gameobject the script doesn’t detect the collisionEnter2d, but when the “obj” falls out of the collider the collisionExit2d works, so the the collisioncount is =-1 instead of 0.
How can I fix this? Thanks in advance!