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
}
}