NullReferenceException causes OnCollisionEnter to not trigger.

Today, I got a line of code on my bullet script to spawn a gameobject called hit, as follows.

`void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == this.gameObject.tag) {
Physics2D.IgnoreCollision (col.collider, col.otherCollider);
}

else {
    GameObject.Instantiate (hit, new Vector2 (rb.transform.position.x, rb.transform.position.y), Quaternion.identity);
    Destroy (this.gameObject);
}

}`

It works in all cases excluding when the bullet is spawned close or partially inside another colider, when this happens, it throws the NullReferenceException error and simply slides on/pushes down on the surface until it hits something else, it doesn’t destroy itself or spawn the hit object.
It probably is a tiny issue I can’t wrap my head around, can anoyone lend a helping hand? This wasn’t a problem until the hit prefab was involved.

Game is 2d if that changes things.

This wasn’t a problem until the hit prefab was involved.

Sounds to me like your ‘hit’ object is null.

Try adding a null check:

if(hit != null)

That being said, with the code provided there’s no way to tell why it’s null when instantiated inside another collider.