- Home /
Collision detected but destroy not working
I suddenly have the weirdest bug which makes me going crazy. I use an invisible Scorezone. When the Player enters this Scorezone, he is scoring some points and the Scorezone destroys itself. Before that, a seconds Scorezone gets destroyed because you can only get one type of Score. So far so good.
This is the very simple code:
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "PerfectScoreZone")
{
var controller = collision.gameObject.GetComponent<SecondScoreZoneController>();
if (controller)
{
Destroy(controller.SecondScoreZone);
}
Score();
Destroy(collision.gameObject);
}
}
The collision gets perfectly detected. The Second Scorezone gets destroyed and the Score()-Method is called everytime. However, sometimes, (not every time which makes this even more difficult to diagnose), the scorezone itself does not get destroyed (last line of code), which makes the zone behave like a physical object moving the player.
And here is another part: when moving the player away from the scorezone and then colliding again, the destroy-method suddenly works.
I did not have this issue before. I somehow must have changed something causing this issue. I would say this issue occurs every 10th time, when the scorezone is touched.
Thank you for your help!
Answer by afot2020 · Jul 19, 2020 at 12:25 PM
UPDATE
Using Debug.Log I found out that collision.GetContacts(contacts)) returns 0 whenever the issue occurs. So the collision seems not to be detected. BUT: why is the if-Statement called after all? The collsion somehow IS detected...
Answer by davidcox70 · Jul 19, 2020 at 03:51 PM
Sometimes I have found that hard-to-resolve bugs around colliders related to a collision being called multiple times - for example as a player skims a collision zone, effectively going in and out rapidly. The solution can be to add and extra condition to the trigger. For example;
if (collision.gameObject.tag == "PerfectScoreZone" && !triggered)
{
triggered=true;
``...
This stops a double trigger. This might not be your issue, but worth a shot. Remember to reset trigger for the next time you need it. DC
Thank you for your tip! What actually solved the issue was calling the Destroy-$$anonymous$$ethod at the beginning of the if-Statement
Your answer
Follow this Question
Related Questions
Why can't I destroy this object!? 3 Answers
Documentation unclear about destroying the object 2 Answers
Why does Destroy(this.gameObject) destroys a prefab that got nothing to do with the script 0 Answers
Trying to apply force to an object 1 Answer
Colliders at wrong position after building the game? 1 Answer