Getting error "NullReferenceException: Object reference not set to an instance of an object" when trying to find closest object.

Hi Iam new to unity and i am trying to make script that print name of the closest object to mouse cursor with tag “joint”.It is based on example at this page: Unity - Scripting API: GameObject.FindGameObjectsWithTag but i have an error
NullReferenceException: Object reference not set to an instance of an object
mouse input.Update () (at Assets/mouse input.js:12)

and i dont know what am i doing wrong… Here is the code:

#pragma strict

var mouseDistance : float = 5;
public var distance = Mathf.Infinity;

function Update () {
	var mousePosition = new Vector3 (Input.mousePosition.x,Input.mousePosition.y,mouseDistance);
	var worldPoint = Camera.main.ScreenToWorldPoint(mousePosition);
	
	 if (Input.GetKey(KeyCode.Mouse0))
	 {
	 	Debug.Log(FindNearestJoint(worldPoint).name);
	 }
	 
}

function FindNearestJoint (curPos : Vector3)
{
	var joints : GameObject [];
	var closest : GameObject;
	joints = GameObject.FindGameObjectsWithTag("Joint");
	
	for (var object : GameObject in joints)
	{
		var diff = (curPos - object.transform.position);
		var curDistance = diff.sqrMagnitude;
		if (curDistance < distance)
		{
			closest = object;
			distance = curDistance;
		}
	}
	
	return closest;
}

Iam sorry for my bad english.

Not sure this is your problem, but if this line:

      joints = GameObject.FindGameObjectsWithTag("Joint");

…fails to find anything, then FindNearestJoint() will return null. In which case this line:

     Debug.Log(FindNearestJoint(worldPoint).name);

…will generate a null reference exception since you are trying to get ‘.name’ from null.

object is a reserved word use something else instead of it and initialize closest when you create it or check null like below to get read of null

 if (Input.GetKey(KeyCode.Mouse0))
      {
          if(FindNearestJoint(worldPoint).name)!=null)
             Debug.log(FindNearestJoint(worldPoint).name);
      }