Camera.main.ScreenPointToRay sometimes causing NullReferenceException

The following script is attached to an object so that I can detect when it has been clicked.

function Update () {

if (Input.GetMouseButtonDown(0)) // check for left-mouse
  {

    var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    var hit : RaycastHit;
    if (collider && collider.Raycast (ray, hit, 100.0))
    {
        Debug.Log("Touched!");
    }
  }
}

The code works fine except that sometimes the line var ray = Camera.main.ScreenPointToRay (Input.mousePosition); causes a NullReferenceException in the Console window. But the game continues normally. Any idea how to correct this behavior?

I was periodically changing between two cameras and one of the cameras was untagged. Tagging it as MainCamera solves the problems. Thanks.