# Why does this raycast code give me a NullReferenceException?

The Error in the code is NullReferenceException: Object reference not set to an instance of an object for if (hitxx.collider.tag == "soldier") Please help! Thanks in advance

 void Update () {
Physics.Raycast (eyeenemy.transform.position, (eyeenemyfront.transform.position - eyeenemy.transform.position) * 20,out hitxx);

Debug.DrawRay (eyeenemy.transform.position, (eyeenemyfront.transform.position - eyeenemy.transform.position) * 20,Color.green);
if (hitxx.collider.tag == "soldier") {
gameObject.transform.LookAt (soldier.transform.position);
Debug.Log ("chuchu");
}


Your hitxx, of type RaycastHit, is only initialized by Physics.Raycast() if it actually hits something. Otherwise it will remain unchanged since the last hit or will be null if nothing has been hit in the past. You are failing to handle the condition in which nothing is hit. When you get to checking the tag, it is trying to access a collider on a null reference.
Physics.Raycast() actually returns a bool representing whether something was hit. You could use that in a condition so be sure that hitxx is not null.
bool isHit = Physics.Raycast (eyeenemy.transform.position,