Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OnCollisionEnter is not called in unity

Tags:

c#

unity3d

I checked nearly every answer for this, but those were mostly simple errors and mistakes. My problem is that OnCollisionEnter is not called even when colliding whith other rigidbody.

here is the part what does not get called:

 void OnCollisionEnter(UnityEngine.Collision col) {
        Debug.Log("collision!!!");
        foreach(ContactPoint contact in col.contacts) {
            //checking the individual collisions
            if(contact.Equals(this.target))
            {
                if(!attacking) {
                    Debug.Log("hitting target");
                } else {
                    Debug.Log("dying");
                    //engage death sequence
                }
            }
        }
    }

Not even the "collision!!!" message appears. Do I understand the usage wrong, or did I forget something?

like image 957
Erik Putz Avatar asked Dec 13 '13 13:12

Erik Putz


3 Answers

Are you using 2D colliders and rigidbodies? If so use this function instead of OnCollisionEnter

void OnCollisionEnter2D(Collision2D coll)
    {
        Debug.Log(coll.gameObject.tag);

    }
like image 131
Khayam Gondal Avatar answered Nov 09 '22 04:11

Khayam Gondal


You need to make sure that the collision matrix (Edit->Project Settings->Physics) does not exclude collisions between the layers that your objects belong to.

Unity Docs

You also need to make sure that the other object has : collider, rigidbody and that the object itself or either of these components are not disabled.

like image 3
Alex Avatar answered Nov 09 '22 05:11

Alex


Try this

http://docs.unity3d.com/Documentation/ScriptReference/Collider.OnCollisionEnter.html

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {
  void OnCollisionEnter(Collision collision) {

    foreach (ContactPoint contact in collision.contacts) {
        Debug.DrawRay(contact.point, contact.normal, Color.white);
    }

    if (collision.relativeVelocity.magnitude > 2){
        audio.Play();        
    }

  }
}
like image 2
Julio Contreras Avatar answered Nov 09 '22 05:11

Julio Contreras