- Home /
Why am I getting this NullReferenceException error when everything seems to be in place ?
I need to spawn an explosion when my object collides with a gameobject under the tag 'Blast', for which I have the following code:
void OnTriggerEnter2D(Collider2D blastCollisionCheck)
{
if (blastCollisionCheck.gameObject.tag == "Blast") {
Spawn (gameObject.transform.position);
}
}
This spawn works alright, but whenever my object collides with a 'killer' gameobject (that just disables my current object) under a different tag, I start getting that NullReferenceException error. Anyone know why ?
Is this the code that's throwing the exception? If you look at the full exception text in the console window, you should see a line number and a stack trace.
Yes. Here is the full exception text that I get. NullReferenceException: Object reference not set to an instance of an object CrowdBehavior.OnTriggerEnter2D (UnityEngine.Collider2D blastCollisionCheck) (at Assets/Scripts/CrowdBehavior.cs:42)
Answer by T27M · May 23, 2014 at 08:29 PM
So with the information in the question this answer is based on a lot of assumption, here is what I think is going on.
I'm assuming your "killer" gameobject does something like
void OnTriggerEnter2D (Collider2D other)
{
other.gameObject.SetActive(false);
}
It seems that when this happens the value stored variable called blastCollisionCheck is lost when the gameobject is disabled. The blastCollisionCheckis variable is now null.
That's where I think the NullReference is coming from. I'll leave it to you to figure out a work around.
Yes, that is exactly what my 'killer' gameobject is doing. And I was right in assu$$anonymous$$g what you suggested that the blastCollisionCheck variable is lost when it is disabled and becomes null. I don't $$anonymous$$d that it becomes null and gets lost. How do I make sure that Unity doesn't keep flagging it as a NullReferenceException everytime this happens ? Also, is it a good habit to allow this to happen ?
You can check to make sure it is not null by surrounding your code with the following statement.
if (blastCollisionCheck != null) {
if (blastCollisionCheck.gameObject.tag == "Blast") {
Spawn (gameObject.transform.position);
}
}
A null reference is bad, because as you have found out it will throw an error, may crash your program and/or lead to other unexpected things happening.
That totally worked like a charm. I will keep a lookout on anything unexpected to be happening, though I doubt it should, since this is the only time that variable is ever used and I won't be accessing it ever again. Thanks for your help, @T27$$anonymous$$
The checking won't cause problems. I meant if you left the null reference in the program it would cause problems, like the one you were having.
Glad I could help ;)
Your answer
