NullReference when checking tag via Raycast. How to solve this?

I’m trying to eliminate the ground (tagged “Ground”) and my player’s transform from a simple raycast which rotates the transform on hit; this is basically to stop my player rotating whenever it raycast hits the ground or itself. I have tried:

  • hit.collider.gameObject.tag != “Ground” and
  • !hit.collider.gameObject.CompareTag(“Ground”)

to check the ground’s tag via raycast hit, but both are causing a NullReferenceException. If I comment out that line in each script there are no errors and the script runs perfectly fine. I have read through almost 2 dozen questions about this both here and on the forums and come up with the two solutions below. So how can I check an objects tag via raycast? These two ways aren’t working:

(Method 1)

using UnityEngine;
using System.Collections;

public class ObstacleAvoidance6 : MonoBehaviour {
	
	public float turnSpeed = 5;
	RaycastHit hit = new RaycastHit();
	
	
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
		if(Physics.Raycast(transform.position, transform.forward, 1)){
			Debug.DrawLine(transform.position, transform.forward, Color.blue);
			if (hit.transform != transform && hit.collider.gameObject.tag != "Ground") {
				transform.Rotate(Vector3.up, 90 * turnSpeed * Time.smoothDeltaTime);
			}
		}
		else {
		
			transform.position += transform.forward * 1 * Time.deltaTime;
		}
	}
}

(Method 2)

using UnityEngine;
using System.Collections;

public class ObstacleAvoidance7 : MonoBehaviour {

	public float turnSpeed = 5;
	RaycastHit hit = new RaycastHit();

	// Use this for initialization
	void Start () {
	}

	// Update is called once per frame
	void Update () {

		if(Physics.Raycast(transform.position, transform.forward, 1)){
			Debug.DrawLine(transform.position, transform.forward, Color.blue);
			if (hit.transform != transform && !hit.collider.gameObject.CompareTag("Ground")) {
				transform.Rotate(Vector3.up, 90 * turnSpeed * Time.smoothDeltaTime);
			}
		}
		else {
			transform.position += transform.forward * 1 * Time.deltaTime;
		}
	}
}

Both of your scripts are actually correct expect for two little things —> out hit,

Add this before the float 1 (don’t forget to add a comma) and both of the scripts should work just fine.