NullreferenceException using Raycasts


Using this code to create the foundations of a basic shooting behaviour.

using UnityEngine;
using System.Collections;

public class Shotingscript : MonoBehaviour {

	public float range = 100f;
	public float Dammage = 50f;
	RaycastHit hit;
	// Use this for initialization
	void Start () {
	// Update is called once per frame
	void Update () {
		Vector3 fwd = transform.TransformDirection(Vector3.forward); //the direction the player is facing
		//Ray Laser = Camera.main.transform.position;
		if(Physics.Raycast(transform.position, fwd, range)){
				Debug.Log ("Fired");
				//	gameObject HP = hit.collider.GetComponent<Healthscript>();
				//hit.collider.SendMessage("ApplyDammage", Dammage, SendMessageOptions.DontRequireReceiver); //Call the method Apply Damage in the gameobject that is hit
				if(hit.collider.GetComponent<Healthscript>() != null && Input.GetButton("Fire1")){
					Debug.Log("Hit Something");

I get this error when I hit a collider:
NullReferenceException: Object reference not set to an instance of an object
Shotingscript.Update () (at Assets/Scripts/Shotingscript.cs:23)

It’s because hit is declared, but not initialized or instantiated to any value. Use the verion of Physics.Raycast that includes an out parameter for the hit.


Physics.Raycast(transform.position, fwd, out hit, range)