When enemy dies the script loses object reference.
So I'm working on a little FPS and right now I have one enemy. When I kill that enemy it says "Object reference not set to an instance of the object. This is the area of code that the error is highlighting:
Vector3 firePointPos = new Vector3(firePoint.position.x, firePoint.position.y, firePoint.position.z);
RaycastHit hit;
Debug.DrawRay(firePointPos, transform.forward, Color.cyan);
if (Physics.Raycast(firePointPos, transform.forward, out hit))
{
Debug.Log(hit.collider.tag);
}
Enemy enemy = hit.collider.GetComponent<Enemy>();
if (enemy != null)
{
enemy.DamageEnemy(damage);
Debug.Log("We hit " + hit.collider + " and did " + damage + " damage");
}
}`
More specifically it is highlighting this line:
Enemy enemy = hit.collider.GetComponent<Enemy>();
Answer by pekalicious · Mar 12, 2016 at 05:06 AM
That line is outside of the if block, so it will run whether you hit a collider or not. So if the raycast fails, hit.collider = null, so it crashes.
You probably need to put everything in that first if statement:
if (Physics.Raycast(firePointPos, transform.forward, out hit))
{
Debug.Log(hit.collider.tag);
Enemy enemy = hit.collider.GetComponent<Enemy>();
if (enemy != null)
{
enemy.DamageEnemy(damage);
Debug.Log("We hit " + hit.collider + " and did " + damage + " damage");
}
}
Great. Glad I help. Can you accept this answer? Thanks.
Your answer
Follow this Question
Related Questions
[Begginer] [Solved] How to solve a Null Reference Exception 1 Answer
NullReferenceException: Object reference not set to an instance of an object 1 Answer
A list of a struct doesn´t saw a word in the console. Object reference, but i dont have anyone 1 Answer
Array of dictionaries: "Object reference not set to an instance of an object" 0 Answers