Stop OnCollisionEnter method from running.

I have a grenade gameobject that explodes only if it hits an enemy directly using OnCollisionEnter. If it doesn’t hit an enemy it waits for a few seconds to explode. But when all enemies are destroyed and a grenade is thrown and explodes it throws missing reference exceptions. So I put in a try and catch statement in the method. But for performance sake I would like Oncollisionenter to STOP trying to run altogether since it runs every frame. It finds enemies by their tag with

GameObject.FindGameObjectWithTag(“Enemy”).GetComponent()
but when there is no enemy this causes the exception. Here is my code. How Can I stop OnCollisionEnter from running after all enemies are destroyed.

void OnCollisionEnter(Collision collision)
    {
        try
        {
            if (collision.collider == GameObject.FindGameObjectWithTag("Enemy").GetComponent<CapsuleCollider>())
            {

                Explode();
                hasExploded = true;
            }               
        }
    catch (NullReferenceException)
                {                    
                    //Do nothing
                }       
    }

Good day.

You are almost there! You recieve a null reference because, with that if sentence, you are trying to get the Capsule collider component, from an object that maybe does not exist.

You need to check if the GameObject.FindGameObjectWithTag(“Enemy”) exist ( do not check directly if the component exists)

So add a simple if with a return before your if sentence, like this:

if (GameObject.FindGameObjectWithTag("Enemy") == null)
{
return;
}

if (collision.collider == GameObject.FindGameObjectWithTag("Enemy").GetComponent<CapsuleCollider>())
             {
 
                 Explode();
                 hasExploded = true;
             }     

Bye!!!