[js]NullReferenceException: Object reference not set to an instance of an object

This is my script:

#pragma strict

var woodPlank : GameObject;
var Player : Transform;
var maxDist : float;

private var InventScript : Inventory;

function Start()
{
	InventScript = GameObject.Find("Player").GetComponent(Inventory);
}

function Update ()
{
	var hit : RaycastHit;
	
	if (Input.GetButtonDown("Fire2") && hit.transform.tag == "PlaceableAreas")
	{
		if ((InventScript.woodAmount - 1) >= 0)
		{
			if (Physics.Raycast(transform.position, transform.forward, hit, maxDist))
			{
				var instantiatedPlank = Instantiate(woodPlank, hit.point, Player.rotation);
				instantiatedPlank.transform.position.y += 1;
				InventScript.woodAmount -= 1;
			}
		}
	}
	
	
}

There is absolutely nothing wrong with this script, but apparently there’s something wrong with hit.transform.tag == "PlaceableAreas" even though the syntax is right, and there is a transform (the terrain) which has the tag PlaceableAreas, and it’s spelled right, it gives me NullReferenceException: Object reference not set to an instance of an object. Why is this?

You say there is nothing wrong with the script. Yet clearly there is since your getting an error =P

Currently you are declaring hit, then attempting to check if hit.transform.tag == “PlaceableAreas” when you click “Fire2”. But hit hasnt been assigned yet! You need to do your raycast before you can check what the raycast hit.

Heres updated code to reflect this:

#pragma strict
 
 
var woodPlank : GameObject;
var Player : Transform;
var maxDist : float;
 
private var InventScript : Inventory;
 
function Start()
{
    InventScript = GameObject.Find("Player").GetComponent(Inventory);
}

function Update()
{
	var hit : RaycastHit;
	
	if(Input.GetButtonDown("Fire2"))
	{
		if(Physics.Raycast(transform.position, transform.forward, hit, maxDist))
		{
			if(hit && hit.transform.tag == "PlaceableAreas" && (InventScript.woodAmount - 1) >= 0)
			{
				var instantiatedPlank = Instantiate(woodPlank, hit.point, Player.rotation);
           		instantiatedPlank.transform.position.y += 1;
               	InventScript.woodAmount -= 1;
			}
		}
	}
}