Raycast tag/ Null reference exception?

I am trying to use a raycast and I want the raycast to be able to differentiate between the player and everything else(the player being tagged as “Player”).

using UnityEngine;
using System.Collections;

public class ai : MonoBehaviour {

	//Bool
	bool monsterRaycast;
	bool patrol = true;
	
	//Transform
	public Transform raycastLocation;
	
	//Raycast
	private RaycastHit hit;
	
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
		monsterRaycast = Physics.Raycast(raycastLocation.position, transform.TransformDirection (Vector3.forward), out hit, 5);
		
		if(hit.transform.tag == "Player")
		{
			patrol = false;
		}
		if(patrol)
		{
			//Do Stuff
		}
		else
		{
			//Do Stuff
		}
	}
}

It obviously isn’t complete but as of now it is saying: NullReferenceException: Object reference not set to an instance of an object.

The error is specifically on this line:
if(hit.transform.tag == “Player”)

Physics.Raycast() returns true if the ray hits something. If it does not hit anything, then your RaycastHit variable (‘hit’) will not be initialized. And if you try and access an uninitialized variable, you get a NullReferenceException. So you have to put lines 26 through 37 inside an if statement. Yo ucan use monsterRaycast if you want.

if (monsterRaycast) {

    if(hit.transform.tag == "Player")
       {
         patrol = false;
       }
       if(patrol)
       {
         //Do Stuff
       }
       else
       {
         //Do Stuff
       }

} 

Note your ‘if’ statement(s) here can be simplified:

 if(hit.transform.tag == "Player")
       {
         // Do non-patrol stuff
       }
      else
       {
         //Do patrol Stuff
       }