Gets a error and code still works

I have this code and it works perfectly fine and everything runs as it should but I still get an error on the line “if(hit.collider.tag == “Ground”){”.

error:

NullReferenceException: Object reference not set to an instance of an object
MouseHandle.Move () (at Assets/Scripts/Handle/MouseHandle.cs:28)
MouseHandle.Update () (at Assets/Scripts/Handle/MouseHandle.cs:17)

It doesn’t stop my working progress but it would be nice to get rid of all the errors that fills the log and make so I can’t see other errors or warnings in the log.
void Move(){

		Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		RaycastHit hit;
		Debug.DrawRay(ray.origin,ray.direction * 100);

		Physics.Raycast(ray,out hit,Mathf.Infinity);
		if(hit.collider.tag == "Ground"){
			if(Input.GetKey(KeyCode.Mouse0) && Input.GetKey(KeyCode.LeftShift)){
				builder.GetComponent<Movement>().MoveTo(hit.point,true);
			}
			else if(Input.GetKey(KeyCode.Mouse0)){
				builder.GetComponent<Movement>().MoveTo(hit.point);
			}
		}
	}

You should always check if Raycast hit something to access the hit object. When your Raycast does not hit something it will return null but your code will work properly since everything else inside your if(hit.collider.tag == “Ground”) will only work when there is actually a hit.

So your code will become:

if(Physics.Raycast(ray,out hit,Mathf.Infinity){
    if(hit.collider.tag == "Ground"){
        if(Input.GetKey(KeyCode.Mouse0) && Input.GetKey(KeyCode.LeftShift)){
        builder.GetComponent<Movement>().MoveTo(hit.point,true);
    }
    else if(Input.GetKey(KeyCode.Mouse0)){
        builder.GetComponent<Movement>().MoveTo(hit.point);
    }
}