Raycast 2D using Debug to check if working

So I have a 2D Raycast and I can’t figure out how to get the Debug to work.
I get the error:

NullReferenceException: Object reference not set to an instance of an object
PlayerStats+$calculateWalk$1+$.MoveNext () (at Assets/Scripts/PlayerStats.js:91)

The line of code it has an issue with is this:

if(hit.collider.tag == "tallGrass")

In other threads I see people saying to have hit.collider != null but if I add that the debug doesn’t work.

I’m using the “Lets Clone a Game [Pokemon]” Tutorial by JesseEtzler0 and I had to convert his 3D Raycast into a 2D Raycast, since I’m using the sprite method over his 3D objects method, and I can’t seem to figure out how to fix it or if there is also something else thats incorrect that I missed.

var hit : RaycastHit2D;
		if(Physics2D.Raycast(transform.position, Vector2.zero, 100.0))
		{
			var distanceToGround = hit.distance;
			Debug.Log("HIT");
		}
		if(hit.collider.tag == "tallGrass")
		{
			Debug.Log("Tall Grass");
		}

Thanks for any help, its much appreciated.

Edit Update:

Okay, so I’ve been trying to figure it and while everything thus far hasn’t worked. I took a break from it and I came back to it and I changed some small things from when we had it as a raycast and it works almost 100%. I had to disable the Box Collider 2D I had on the character as well.

Issue now is it doesn’t debug either ‘HIT’ or ‘Tall Grass’ when I move the character right. It shows perfectly fine when I move up, down, and left but for some reason moving right doesn’t show the debug.

I don’t know if its some weird bug I’m having or what.

Current Code:

 var hit : RaycastHit2D = Physics2D.Raycast(transform.position, Vector2.zero);
     //Debug.DrawLine(transform.position, Vector3.zero, Color.white, 5f, false);
     
         if(hit != null)
         {
             var distanceToGround = hit.distance;
             Debug.Log("HIT");
             if(hit.collider != null && hit.collider.tag == "tallGrass")
             {
                 Debug.Log("Tall Grass");
             }
         }

You need to put your if(hit.collider.tag == “tallGrass”) inside your if(Physics2D.Raycast(transform.position, Vector2.zero, 100.0)) since hit variable is available only inside the if statement of Physics2D.Raycast().

So your code becomes:

var hit : RaycastHit2D;
if(Physics2D.Raycast(transform.position, Vector2.zero, 100.0))
{
    var distanceToGround = hit.distance;
    Debug.Log("HIT");
    if(hit.collider.tag == "tallGrass")
    {
        Debug.Log("Tall Grass");
    }
}