title: C# raycast code not working with Unity
body: <p>Hi so I wrote some code to create a raycast that follows the mouse position on the screen, I have the gun set up and I have the barrel down properly with a collider etc, but I keep getting the error:
  NullReferenceException: Object reference not set to an instance of an object.
  I just can't work out what the problem is, here's my code:</p>
  
  <pre><code>    void Update ()
      {
          if (gun.active) {
                      if (Input.GetButtonDown ("Fire1")) {
                              Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
                              RaycastHit hit = new RaycastHit ();
                              if (Physics.Raycast (ray, out hit)) {
                                      if (hit.collider.gameObject.name == "barrel") {
                                              Debug.Log ("Hit the Barrel");
                                              Destroy (hit.collider.gameObject);
                                      }
                              }
                      }
              }
  
      }
  </code></pre>