OnCollisionEnter2D doesn't detect collisions.

Hi , im fairly new at Unity and last night i tried to create a bullet script that would

Destroy itself on impact
Deal damage to Player

But , even though the bullets collide with the Player, the OnCollisionEnter doesnt work.

Here is my script,

public class collision : MonoBehaviour {

    PlayerHealth playerHealth;

 
    public int bulletDamage;
    public bool bulletHit;



    void OnCollisionEnter2D (Collision2D col)
    {

        if (col.gameObject.tag == "Player" )
        {
            playerHealth.TakeDamage(bulletDamage);

            Destroy(gameObject);

            bulletHit = true;
        }


    }


}

I have no problems with my bullets being ejected. Heres some screenshots of bullets colliding with a collider and rigidbody

edit: my main players tag is definitely Player , bulletHit bool simply was to understand if the
OnCollisionEnter2D was working. It never went off

I fixed the issue since i posted here.

I was trying to get a script bound to another game object. But because my Bullet object was a prefab, it couldnt find the gameObject the PlayerHealth script was attached to.

Adding the string;

playerHealth = GameObject.FindObjectOfType(typeof(PlayerHealth)) as PlayerHealth;

on the Start() fixed the issue

1 Like

Finding a component that way is inefficient. In your first script, on collision, you have the game object that the bullet is colliding with. I’d recommend then getting the PlayerHealth script from that game object instead.

playerHealth = collision.gameObject.GetComponent<PlayerHealth>();
if (playerHealth != null) {
  playerHealth.TakeDamage(this.bulletDamage);
}

In 3D, I’ve had better operation with OnCollisionEnter / Exit as they trigger on touch already.

I believe that OnCollisionEnter is meant to only be used in 3D and OnCollisionEnter2D is meant to only be used in 2D.

1 Like