Random Chance NullReferenceException: Object reference not set to an instance of an object
I am making a game where you have to shoot enemies, and the projectiles shot explode on impact. I've got everything implemented, but for some reason, this error has a random chance of appearing. For the life of me, I cannot see a pattern in how this appears. Here is the full error:
NullReferenceException: Object reference not set to an instance of an object Projectile.OnFireballExplode () (at Assets/Scripts/Projectile.cs:25) Projectile.OnCollisionEnter (UnityEngine.Collision collision) (at Assets/Scripts/Projectile.cs:13)
And here is the script on where the error occurs:
using UnityEngine;
using System.Collections;
public class Projectile : MonoBehaviour {
public GameObject explosionObject;
public float blastRadius = 10f;
private GameObject explosion;
void OnCollisionEnter(Collision collision) {
explosion = Instantiate(explosionObject, transform.position, transform.rotation) as GameObject;
OnFireballExplode();
explosion.transform.parent = GameObject.Find("Explosions").transform;
Destroy(gameObject);
}
void OnFireballExplode()
{
GameObject[] enemies = GameObject.FindGameObjectsWithTag("enemy");
foreach (GameObject enemy in enemies) {
if (blastRadius >= Vector3.Distance(transform.position, enemy.transform.position)) {
enemy.GetComponent<Health>().DealDamage(50f);
}
}
}
}
The error occurs on the last line:
enemy.GetComponent<Health>().DealDamage(50f);
Even though every enemy has a health script, it still calls. Does anyone know why this is? Again, its odd. Sometimes it calls, sometimes it doesn't. Thank you!
First i think you should find out exactly what is null. Split that line into two so you see whether enemy is null or if it's the GetComponent. There shouldn't be a way for enemy to be null i think but still.
Does DealDamage call Destroy on something? Does it destroy the gameObject or perhaps just the script?
In any case add some Debug.Logs to see if some enemy gets destroyed multiple times or such
Does it still crash if you change the line to
if(enemy!=null && enemy.GetComponent<Health>()!=null) {
enemy.GetComponent<Health>().DealDamage(50f);
}
? (Note that this is not a solution to your problem, because if enemy or the Health-component are null there is probably something wrong at another place in your code. It is just for testing purposes.) If the error still occurs you should provide the code of DealDamage.
Answer by Morgenstern_1 · Jun 24, 2016 at 10:31 AM
You could have accidentally applied the "enemy" tag to something in your scene that doesn't have a Health component. Are your enemies made up of multiple components? Perhaps it's a child object of an enemy that doesn't have a health component itself.
I feel obliged to say that your code is quite inefficient too... GameObject.Find should almost never be used unless there's absolutely no other option. And even if you must use it you should cache the result unless it's going to change.
Vector3.Distance is really expensive too... if you change the code to what I've put below you'll get the same end result much cheaper :)
if (blastRadius * blastRadius >= Vector3.SqrMagnitude(transform.position - enemy.transform.position))
Answer by StormMuller · Jun 24, 2016 at 01:24 PM
So as @Morgenstern_1 pointed out, You might have a gameObject in your scene that is not an enemy but you have accidentally set it as the enemy. Also like he said your enemy prefab might have child gameObjects that are also tagged as "enemy", is this is the case then all your children And parent gameobjects are getting added to your enemies
list and therefore it is looking for a Health
component in every single one. To fix this just remove the enemy tag from the child gameobject(s) in your prefab. If you intended to tag the children as "enemy" then you can just replace this:
enemy.GetComponent<Health>().DealDamage(50f);
with this:
Health hp = enemy.GetComponent<Health>();
if(hp != null)
{
hp.DealDamage(50f);
}
Also you should cache your gameobjects and not use any .FindX() methods unless you need to, this is also simple to do, Instantiate()
returns a GameObject, so we can do this in your spawning script:
static List<GameObject> enemies;
void Start()
{
enemies = new List<GameObject>();
}
void Update()
{
if(/* Spawn condition here */)
{
enemies.Add(Instantiate(/* Your enemy prefab variable */));
}
}
and then to use this in your projectile script:
public class Projectile : MonoBehaviour {
/* Other methods you made */
void OnFireballExplode()
{
// GameObject[] enemies = GameObject.FindGameObjectsWithTag("enemy");
// be sure to change this to the correct script name for your project
foreach (GameObject enemy in SpawnScript.emeies) {
if (blastRadius * blastRadius >= Vector3.SqrMagnitude(transform.position - enemy.transform.position)) {
enemy.GetComponent<Health>().DealDamage(50f);
}
}
}
And just remeber to call SpawnScript.enemies.Remove(/* the enemy game object that got destroyed */);
when your enemy's health is at 0f;
So I hope this helped you fix your null reference error and optimized your code a little bit.