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
}
}
Answer by tormentoarmagedoom · Aug 25, 2018 at 10:29 AM
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!!!
Your answer
![](https://koobas.hobune.stream/wayback/20220612173430im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
how to spawn unityads every 5 time i die? 1 Answer
End Game (Stop spawning) with OnTriggerEnter or OnCollisionEnter? 0 Answers
C# OnCollisionEnter2D failing to respond 1 Answer
How to snap/ joint multiple cubes on each side but perfectly aligned, 0 Answers
NullReferenceException when using gameObject.SetActive(false); 0 Answers