Reputation: 1209
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:
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);
}
}
}
}
}
Upvotes: 0
Views: 1219
Reputation: 7824
Your Camera
is not tagged as main
camera in the Editor.
That is why your code can't find it and thus why it throws an exception.
Upvotes: 4