- Home /
Collision problem when spawning in the collider
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! ;)
Answer by KubaPrusak · Sep 22, 2014 at 06:18 PM
Have you seen what happens when you spawn the gameobject at tiny bit above the "obj" gameobject eg 0.0001
I think it doesnt detect the first enter because you instantiated it inside another gameobject.
yes that's the problem. How can I detect it if it instantiates inside the collider?
Your answer
Follow this Question
Related Questions
Best practice for OnTriggerEnter detection 1 Answer
Trigger or Colission not work if inside volume 2 Answers
Detecting Trigger Collision for Mecanim Animator 0 Answers
How to implement ECS trigger collisions? (Unity.Physics 0.50) 1 Answer
How come the Trigger teleports when its not supposed to! 1 Answer