Trying to be specific on a ray cast hit, getting an error returned

I’m trying to make it so the mouse over event in the if statement only happens when it detects an object with a certain tag. I’ve used this trick successfully before, but this time it’s returning errors for this script which is attempting to simply drag and drop the item.

#pragma strict

var firing: 			boolean = false;

var projectileSocket: 	Transform;
var projectile:			Transform;


function Update () 
{
	var hit : RaycastHit;																	// sets var for raycast
	var ray = Camera.main.ScreenPointToRay ( Input.mousePosition );
	
	if (hit.collider.gameObject.tag == "pigLauncher" && Input.GetMouseButton(0))
	{
		ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		if (Physics.Raycast(ray, hit))
		{
			transform.position.x = hit.point.x;
			transform.position.y = hit.point.y;
		}
	}
	if (Input.GetMouseButtonDown(1))
	{
		firing = true;
	}
	if ( firing )
	{
		FirePiggy ();
	}
}

function FirePiggy ()
{
	Instantiate (projectile, projectileSocket.transform.position, projectileSocket.transform.rotation);
	firing = false;
	yield WaitForSeconds (1.35);
}

This is returning the error;

NullReferenceException: Object reference not set to an instance of an object
pigCatapult.Update () (at Assets/Scripts/pigCatapult.js:18)

regarding this line; if (hit.collider.gameObject.tag == "pigLauncher" && Input.GetMouseButton(0))

But if I’m reading it right, “hit” is referanced as a RaycastHit? So I’m not sure why I’m getting this error.

Any help would be appreciated!

It’s because you are checking if your raycast has hit the tag collider, and THEN firing the raycast. You can’t check what the raycast has hit if you haven’t fired it yet:

if (hit.collider.gameObject.tag == "pigLauncher" && Input.GetMouseButton(0))
    {
       ray = Camera.main.ScreenPointToRay(Input.mousePosition);
       if (Physics.Raycast(ray, hit))
       {

You need to swap these two around:

function Update () {

var hit : RaycastHit;
var ray = Camera.main.ScreenPointToRay ( Input.mousePosition );

if (Physics.Raycast(ray, hit)){
	
	if (hit.collider.gameObject.tag == "pigLauncher" && Input.GetMouseButton(0)){

		transform.position.x = hit.point.x;
		transform.position.y = hit.point.y;
	}

}

See how I’m firing the raycast first?

if (Physics.Raycast(ray, hit)){

And then check to see what it has hit:

if (hit.collider.gameObject.tag == "pigLauncher" && Input.GetMouseButton(0)){

You’re using the hit variable before you actually raycast. I would make it like this instead:

if(mouse pressed)
{
   do a raycast;
   if(hit.object.tag == "desired tag")
   {
      do stuff;
   }
}