- Home /
My OnCollisionEnter says i have 128 Collisions every collision
So I have a Rigidbody2D and a 2D Capsule collider on my object. I also have a script with
private void OnCollisionEnter2D(Collision2D collision)
{
List<ContactPoint2D> _contactPoints = new List<ContactPoint2D>();
collision.GetContacts(_contactPoints);
Debug.Log(_contactPoints.Count);
for (int i = 0; i < _contactPoints.Count; i++)
{
//Checking some stuff
}
}
The problem is that my _contactPoints List always has a count of 128, which includes the collisions they are making right now, but the rest are just collisions with point(0, 0). This means that most of the time my loop is aimlessly iterating over 126 fake collisions.
I have only thought up the solution of deleting the other collisions before the loop, but this just feels like a quick fix.
Does anyone know any way to get the accurate number of collisions from the collision parameter within OnCollisionEnter2D?
I'm not sure what you mean by number of collisions but Collision2D.contactCount (from ver 2018.2) gives the number of contacts in the OnCollisionEnter2D collision. Also the list you give as a parameter might not work as intended. You can use contactCount to deter$$anonymous$$e and set the size of list before passing it to the GetContacts method.
Answer by Spip5 · Aug 14, 2020 at 12:00 AM
Can you try this ?
private void OnCollisionEnter2D(Collision2D collision)
{
ContactPoint2D[] _contactPoints = collision.contacts;
Debug.Log(_contactPoints.Length);
for (int i = 0; i < _contactPoints.Length; i++)
{
//Checking some stuff
}
}
Thank you, that works and for anyone wondering how the code looks like now:
private void OnCollisionEnter2D(Collision2D collision)
{
ContactPoint2D[] _contactPoints = new ContactPoint2D[collision.contactCount];
collision.GetContacts(_contactPoints);
Debug.Log(_contactPoints.Length);
for (int i = 0; i < _contactPoints.Length; i++)
{
//Checking some stuff
}
}
I changed collision.contacts to GetContacts(), since Unity recommends that
Alright, i didnt know it's recommended, glad that works :).
Your answer
Follow this Question
Related Questions
Problem with method Collider2D.isTouchingLayers() 4 Answers
How to make different actions using OnMouseDrag with two different colliders on one Game Object. 0 Answers
Physics2D bug or something I can avoid? 3 Answers
Bullets go through collider even with continuous collision detection! 0 Answers
How do I stop characters from standing on top of each other 1 Answer